在Oracle中获取最大出现的行

时间:2017-07-31 15:19:55

标签: sql oracle

我有一张表:

SALES

PROD_CODE   SALE_ID 
321         30
123         67
321         46
321         82
123         48
321         91

代码:

SELECT PROD_CODE, COUNT(SALE_ID) AS TOTAL_SALES
FROM SALES
GROUP BY PROD_CODE
ORDER BY COUNT(SALE_ID) DESC;

输出结果为:

PROD_CODE  TOTAL_SALES
321        4
123        2

但是,当我期待只有最大销售数量的prod_code作为输出时,

像:

PROD_CODE
321

代码:

SELECT PROD_CODE
FROM (SELECT MAX(COUNT(SALE_ID)) FROM SALES
GROUP BY SALE_ID);

代码无效!

1 个答案:

答案 0 :(得分:4)

在Oracle 12c +中,您可以这样做:

select s.prod_code
from sales s
order by count(*) desc
fetch first 1 row only;

在早期版本中,

select s.*
from (select s.prod_code
      from sales s
      order by count(*) desc
     ) s
where rownum = 1;

或者:

select max(prod_code) over (dense_rank first order by cnt desc)
from (select s.prod_code, count(*) as cnt
      from sales s
      group by s.prod_code
     ) s

前两个版本获取整行。您可以将其限制为一列或多列,这就是您想要的。