嵌套聚合在Ent查询中。

huangapple go评论89阅读模式
英文:

Nested aggregation in Ent Query

问题

你好!以下是翻译好的内容:

如何使用Ent生成的代码编写这个简单的SQL语句?

select max(t.sum_score) from
                             (select sum(score) as "sum_score"
                              from matches
                              group by team) as t

我尝试使用自定义SQL修饰符功能标志,如这里所述,但我无法弄清楚如何从修饰符之外访问sum_score字段。

英文:

How can I write this simple SQL statement using the code generated by Ent?

select max(t.sum_score) from
                             (select sum(score) as "sum_score"
                              from matches
                              group by team) as t

I tried to use Custom SQL Modifiers feature flag as described here but I can't figure out how to access the sum_score field from outside of the modifier.

答案1

得分: 0

这是来自 Ent 项目所有者 a8m 的答案(谢谢!)

client.Match.Query(). 
	Aggregate(func(s *sql.Selector) string {
		const as = "max_score"
		s.GroupBy(match.FieldTeam).OrderBy(sql.Desc(as)).Limit(1)
		return sql.As(sql.Sum(match.FieldScore), as)
	}).
	IntX(ctx)

你可以在官方 GitHub 仓库的这里找到完整的答案。
我不得不添加 sql.Desc(as) 来获取最大值。

英文:

This is the answer from a8m the owner of the Ent Project (thank you!)

client.Match.Query().
	Aggregate(func(s *sql.Selector) string {
		const as = "max_score"
		s.GroupBy(match.FieldTeam).OrderBy(sql.Desc(as)).Limit(1)
		return sql.As(sql.Sum(match.FieldScore), as)
	}).
	IntX(ctx)

You can find the full answer here on the official GitHub repo.
I had to add sql.Desc(as) to get the maximum value.

huangapple
  • 本文由 发表于 2023年3月13日 20:19:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75721786.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定