SQL GROUP BY问题
我有一张桌子:
<代码> 组 ID 数据
1 a 10
2 a 20
3 b 10
4 b 20
我想获取按“group”分组的最大“data”值的记录ID,即
编号
2
4
I have a table:
id group data
1 a 10
2 a 20
3 b 10
4 b 20
I want to get ids of records with max "data" value grouped by "group", i.e.
id
2
4
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用 CTE 的更现代的答案:
PostgreSQL 有一些相当不错的在线文档,请查看 窗口函数和WITH查询。在这种情况下,我们根据表中的行所属的组对它们进行分区。在每个分区中,我们根据数据列对行进行编号(行号 1 分配给最高数据值)。
在外部查询中,我们只要求在其分区内分配行号1的行,如果遵循逻辑,它一定是每个组内的最大数据值。
如果您需要处理关系(即,如果一个组中的多行都具有该组的最大数据值,并且您希望两者都出现在结果集中),您可以从
ROW_NUMBER()
到RANK()
A more modern answer using CTEs:
PostgreSQL has some pretty decent documentation online, look at window functions and WITH queries. In this case, we partition the rows in the table based on which group they belong to. Within each partition, we number the rows based on their data column (with row number 1 being assigned to the highest data value).
In the outer query, we just ask for the rows which were assigned row number 1 within their partition, which if you follow the logic, it must be the maximum data value within each group.
If you need to deal with ties (i.e. if multiple rows within a group both have the maximum data value for the group, and you want both to appear in your result set), you could switch from
ROW_NUMBER()
toRANK()
便携式解决方案:
PostgreSQL解决方案:
PS:我将列名从
group
更改为grp
,因为group
是保留字。如果您确实想要使用group
,则必须引用它。Portable solution:
PostgreSQL solution:
PS: I changed the column name from
group
togrp
becausegroup
is a reserved word. If you really want to usegroup
you'll have to quote it.