id: aggregate

title: Aggregation

Group By

所有用户按照 nameage 分组(Group by),并计算他们的年龄之和。

  1. package main
  2. import (
  3. "context"
  4. "<project>/ent"
  5. "<project>/ent/user"
  6. )
  7. func Do(ctx context.Context, client *ent.Client) {
  8. var v []struct {
  9. Name string `json:"name"`
  10. Age int `json:"age"`
  11. Sum int `json:"sum"`
  12. Count int `json:"count"`
  13. }
  14. err := client.User.Query().
  15. GroupBy(user.FieldName, user.FieldAge).
  16. Aggregate(ent.Count(), ent.Sum(user.FieldAge)).
  17. Scan(ctx, &v)
  18. }

根据单个字段分组。

  1. package main
  2. import (
  3. "context"
  4. "<project>/ent"
  5. "<project>/ent/user"
  6. )
  7. func Do(ctx context.Context, client *ent.Client) {
  8. names, err := client.User.
  9. Query().
  10. GroupBy(user.FieldName).
  11. Strings(ctx)
  12. }