我有一张桌子t1
site| count1 | count2
aaa | 1100 | 500
aaa | 1000 | 400
bbb | 1500 | 700
bbb | 1200 | 600
我想获得与站点value(1100)
对应的列aaa
最高的行
我正在寻找类似的东西
select max(count1),count2 from t1 where site=aaa
答案 0 :(得分:2)
您可以使用LAST
聚合函数
SELECT site
,MAX(count1)
,MAX(count2) KEEP (DENSE_RANK LAST ORDER BY count1) as count2
FROM t1
WHERE site = 'aaa'
GROUP BY site
或row_number()
SELECT site
,count1
,count2
FROM (
SELECT t1.*
,row_number() OVER (
ORDER BY count1 DESC
) as rn
FROM t1 WHERE site = 'aaa'
)
WHERE rn = 1;
OR FETCH FIRST n ROWS ONLY
(Oracle 12c +)
SELECT site
,count1
,count2 FROM t1
WHERE site = 'aaa'
ORDER BY count1 DESC FETCH FIRST 1 ROWS ONLY;
为考虑平局,您可以选择使用dense_rank()
或rank()
代替12c中的row_number()
或WITH TIES
当您要使用多个site
(而不仅仅是'aaa'
)时,应在PARTITION BY SITE
内添加OVER()
OR MAX
分析函数
SELECT site
,count1
,count2
FROM (
SELECT t1.*
,MAX(count1) OVER (PARTITION BY SITE) AS max_count1
FROM t1
WHERE site = 'aaa'
)
WHERE count1 = max_count1