返回总和和平均使用空间

返回总和和平均使用空间

本文介绍了返回总和和平均使用空间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的表的结构如下:

@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?

推荐答案

您正在从方法getUserFitnessSumAndAverageForLastThirtyDays()返回UserFitnessDailyRecords条目.但是查询选择的列不会返回该类型的对象.

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.

请记住在SQL查询中使用"AS"关键字来生成与POJO变量名称匹配的列名称别名.

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

您可以从该方法返回POJO,也许像这样:

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

科特林的方式:

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

Java方式:

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

这篇关于返回总和和平均使用空间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 20:23