代码之家  ›  专栏  ›  技术社区  ›  Aldridge1991

Room SQL查询以检索实体键和值的总和

  •  0
  • Aldridge1991  · 技术社区  · 6 年前

    我的数据库包含这些“移动”类的列表:

    @PrimaryKey (autoGenerate = true)
    private int NumeroDeOperacion;
    private int FechaYear;
    private int FechaMonth;
    private int FechaDay;
    private String TipoOperacion;
    private String Category;
    private String Notas;
    private float Quantity;
    

    在我的一个查询中,我只想检索 Category Quantity 所以我创建了另一个pojo对象,如下所示:

    public class Category {
    
        @ColumnInfo(name = "Category")
        public String name;
    
        @ColumnInfo(name = "Quantity")
        public float quantity;
    
        public Category(){}
    
    }
    

    我想得到的是完全不同的 类别 在一个特定的年份和所有 数量 .

    所以,假设我有这样的东西:

    Category   Quantity
    
    A          5
    B          10
    C          5
    A          15
    B          20
    

    我想知道:

    Category   Quantity
    
    A          20
    B          30
    C          5
    

    我尝试了这个查询,但它只获取每个查询的最后一个条目 类别 :

    @Query("SELECT DISTINCT Category, Quantity FROM OperacionesTable WHERE FechaYear = :year GROUP BY CategoryORDER BY Quantity DESC")
    LiveData<List<Category>> getGastosCategoryTotalsInYear(int year);
    

    任何帮助都将不胜感激。

    提前谢谢

    1 回复  |  直到 6 年前
        1
  •  0
  •   GolezTrol    6 年前

    要计算数量,必须使用 SUM .

    而且,没有必要 DISTINCT ,因为 GROUP BY 已经处理好了。我猜你添加了distinct,因为有一个错误。存在错误,因为数量既不在“分组依据”列中,也不在聚合函数中使用。这通常是一个错误(MySQL中除外,它只会给您一个随机结果)。

    不管怎样,这应该可以做到:

    SELECT 
      Category, 
      SUM(Quantity) as TotalQuantity -- Column alias, to give the column a proper name
    FROM 
      OperacionesTable 
    WHERE 
      FechaYear = :year 
    GROUP BY 
      Category
    ORDER BY SUM(Quantity) DESC