return sum and average using room
Asked Answered
V

1

11

My table is structure is as follows:

@Entity(tableName = "userFitnessDailyRecords")

public class UserFitnessDailyRecords {



    @NonNull
    @PrimaryKey
    private Date forDay;
    private int stepCount;
}

The query I am writing for getting sum and average is as follows:

@Dao
public interface UserFitnessDailyRecordsDao {


    @Query("SELECT SUM(stepCount), AVG(stepCount) FROM userFitnessDailyRecords where forDay BETWEEN :startDay AND :endDay ORDER BY forDay ASC")
    UserFitnessDailyRecords getUserFitnessSumAndAverageForLastThirtyDays(Date startDay, Date endDay);


    @Query("DELETE FROM userFitnessDailyRecords")
    void deleteUserFitnessDailyRecord();

}

Upon compiling I get an error unable to return values as columns do not contain sum and average field. How does one return sum and average in this case?

Volant answered 11/6, 2018 at 15:48 Comment(0)
E
25

You are returning a UserFitnessDailyRecords entry from your method getUserFitnessSumAndAverageForLastThirtyDays(). But the columns selected by your query are not returning an object of that kind.

Remember the use of "AS" keyword in your SQL query to generate columns names aliases that matches the names of your POJO variables.

You can return instead a POJO from that method, maybe like this:

The Kotlin way:

data class SumAveragePojo(var total: Float, var average: Float)

The Java way:

class SumAveragePojo
{ 
    public float total;
    public float average;
}

and change the method return type like this:

@Query("SELECT SUM(stepCount) as total, AVG(stepCount) as average FROM userFitnessDailyRecords where forDay BETWEEN :startDay AND :endDay ORDER BY forDay ASC")
SumAveragePojo getUserFitnessSumAndAverageForLastThirtyDays(Date startDay, Date endDay);
Enneahedron answered 11/6, 2018 at 16:25 Comment(1)
I was already using pojo was not aware of column name alias using "as". This worked :)Volant

© 2022 - 2024 — McMap. All rights reserved.