return sum and average using room

筅森魡賤 提交于 2020-05-13 06:19:40

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/50801617/return-sum-and-average-using-room

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!