房间-通过字符串查找对象的总和?

时间:2019-03-30 10:06:20

标签: android android-room

我在会议室中查询有问题。我有实体在哪里字符串字段称为类型。我想进行一个查询,使我可以按类型获取对象的总和。因此,如果我有4种账单类型的费用,我希望将其作为一笔款项。

费用:

@Entity(tableName = "expense_table")
public class Expense  {

@PrimaryKey(autoGenerate = true)
private int expenseId;
private String note;
private Double value;
private String type;

已定义类型的表

private String[] expenses = {"Bills", "Car", "Child", "Clothes", "Entertainment", "Education", "Electronics",
        "Food", "Health", "Home", "Pet", "Shopping", "Transport", "Travel", "Others"};

在道中查询:

@Query("SELECT SUM(value) FROM expense_table GROUP BY type")
LiveData<List<Double>> getTotalType();

在上面的查询中,我得到了每种类型的总和,但我不知道哪种是哪种。我需要此信息,因为我想在图表中设置类型总和。所以我的问题是:是否可以进行一个查询以获取具有类型名称的每个总和,或者我需要针对每种类型进行每个查询?

1 个答案:

答案 0 :(得分:0)

您需要将类型添加到查询中,并创建一个POJO来保存两个值(类型及其对应的总计):

@Query("SELECT type, SUM(value) as total FROM expense_table GROUP BY type")
LiveData<List<TypeWithSum>> getTotalType();

TypeWithSum为:

public class TypeWithSum {
   private String type;
   private double total;

   public TypeWithSum(String type, double total) {
       this.type = type;
       this.total = total;
   }
}