Oracle-参考where子句

时间:2018-07-23 16:03:53

标签: sql oracle oracle11g

我有一张桌子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

1 个答案:

答案 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

SQL Fiddle Demo