仅显示具有最大计数值的行
我试图从以下查询中仅提取最大计数的行:
SELECT FOO, BAR, COUNT(X)
FROM TABLE1, TABLE2, TABLE3
WHERE <CONDITIONS INVOLVING THE 3 TABLES>
GROUP BY FOO, BAR;
这会生成如下所示的输出 -
FOO | BAR | COUNT(X)
0 String 1 5
1 String 2 3
2 String 3 5
3 String 4 4
4 String 5 5
如您所见,有 3 行的 COUNT(X) 值为 5。我如何将其编辑为只显示包含 MAX(COUNT(X)) 的行?我正在使用 Oracle SQL。
I'm trying to extract only the rows with the maximum count from the following query:
SELECT FOO, BAR, COUNT(X)
FROM TABLE1, TABLE2, TABLE3
WHERE <CONDITIONS INVOLVING THE 3 TABLES>
GROUP BY FOO, BAR;
Which generates output that looks like -
FOO | BAR | COUNT(X)
0 String 1 5
1 String 2 3
2 String 3 5
3 String 4 4
4 String 5 5
As you can see, there are 3 rows with a COUNT(X) value of 5. How would I edit this to ONLY display the rows that contain MAX(COUNT(X))? I am using Oracle SQL.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用分析函数来做到这一点。首先找到每组值的计数,就像您已经做的那样;然后使用
DENSE_RANK()
(或RANK()
或ROW_NUMBER()
) 函数为现有结果中的每一行分配顺序根据COUNT()
值设置基础;最后只选择排名最高的:注意
ORDER BY
中的DESC
,因此最高的COUNT()
被分配给排名1。You can do this with analytic functions. First find the count as for each set of values, as you are already; then use a
DENSE_RANK()
(orRANK()
, orROW_NUMBER()
) function to assign an order to each rows in your existing result set base on theCOUNT()
value; and finally only pick the ones with the highest rank:Note the
DESC
in the theORDER BY
, so the highestCOUNT()
is assigned the rank of 1.这应该有效:
This should work: