说我有以下查询......
SELECT key, MAX(count)
FROM (SELECT key, COUNT(*) count
FROM table INNER JOIN table2 ON
table.fld1 = table2.fld1
GROUP BY key)
我正在尝试获取所有可能的密钥及其MAX(计数),但我不会看到rownum在这种情况下工作,因为有两个密钥可能共享相同的最大COUNT(*),例如以下两个键200和202共享最大值......
key COUNT(*)
200 5
202 5
308 3
309 2
在这种情况下,我的查询输出应该是......
200 5
202 5
我无法使用聚合函数来完成此任务。
答案 0 :(得分:2)
我会使用分析函数来解决这个问题:
select key, cnt
from (select key, count(*) as cnt,
dense_rank() over (order by count(*) desc) as seqnum
from table t
group by key
) t
where seqnum = 1;
答案 1 :(得分:1)
试试这个(任何数据库):
SELECT key, COUNT(*) count
FROM table
JOIN table2 ON table.fld1 = table2.fld1
GROUP BY key
HAVING count(*) = (
select max(count) from (
SELECT key, COUNT(*) count
FROM table
JOIN table2 ON table.fld1 = table2.fld1
GROUP BY key) x)
或者支持常量表表达式的数据库(oracle,sqlserver等):
WITH cte AS (
SELECT key, COUNT(*) count
FROM table
JOIN table2 ON table.fld1 = table2.fld1
GROUP BY key)
SELECT * FROM cte
WHERE count = (SELECT MAX(count) FROM cte)
哪个应该更有效率。