我的表格结构如下:
@Entity(tableName = "userFitnessDailyRecords")
public class UserFitnessDailyRecords {
@NonNull
@PrimaryKey
private Date forDay;
private int stepCount;
}
我写的用于获得总和和平均值的查询如下:
@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();
}
编译后,我收到错误,无法返回值,因为列不包含sum和average字段。在这种情况下,如何归还总和和平均值?
答案 0 :(得分:4)
您正在从方法getUserFitnessSumAndAverageForLastThirtyDays()返回UserFitnessDailyRecords条目。但是查询选择的列不会返回该类型的对象。
请记住在SQL查询中使用“AS”关键字来生成与POJO变量名称匹配的列名别名。
您可以从该方法返回POJO,也许是这样:
Kotlin方式:
data class SumAveragePojo(var total: Float, var average: Float)
Java方式:
class SumAveragePojo
{
public float total;
public float average;
}
并更改方法返回类型,如下所示:
@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);