如何获取Ent中数字列的总和

How to get the sum of numeric column in Ent

我有两个 table:productsbaskets,它们具有 M2M 关系并且 table 名称是 basket_products .我正在尝试获取与特定篮子相关的 products 总计 price 和数量,但我再次陷入困境。如何修复以下代码以获得结果?注意:我使用的是 Ent 框架

   err = client.Basket.
        Query().
        Where(basket.ID(2)).
        WithProducts().
        QueryProducts().
        GroupBy("price").
        Aggregate(func(selector *sql.Selector) string {
            return sql.As(sql.Sum("price"), "price")
        }).Scan(ctx, &r)
    if err != nil {
        log.Println(err)
    }
    log.Println(r)

您是否尝试将 GroupBy("price") 更改为 GroupBy(Basket.FieldPrice) 即通过生成的字段名称引用字段。 按边分组的示例应该类似于 https://entgo.io/docs/aggregate/

AggregateGroupBy函数是朋友。 Aggregation | Ent

我修改了下面给出的代码并得到了一个非常优化的 SQL 查询,感谢 Ent 团队。

err := client.Basket.
        Query().
        Where(basketEntity.ID(ID)).
        GroupBy(basketEntity.FieldID).
        Aggregate(func(s *sql.Selector) string {
            t := sql.Table(product.Table)
            joinT := sql.Table(basketEntity.ProductsTable)
            s.Join(joinT).
                On(s.C(basketEntity.FieldID), joinT.C(basketEntity.ProductsPrimaryKey[0]))
            s.Join(t).
                On(t.C(product.FieldID), joinT.C(basketEntity.ProductsPrimaryKey[1]))
            return sql.As(sql.Sum(t.C(product.FieldPrice)), "price")
        }).
        Aggregate(repository.Count()).
        Scan(ctx, &report)

生成的SQL:

SELECT "baskets"."id", SUM("t2"."price") AS "price", COUNT(*) 
FROM "baskets" 
JOIN "basket_products" AS "t1" ON "baskets"."id" = "t1"."basket_id" 
JOIN "products" AS "t2" ON "t2"."id" = "t1"."product_id" 
WHERE "baskets"."id" =  
GROUP BY "baskets"."id" args=[1]