从事件组中选择最大计数

时间:2017-08-11 12:21:27

标签: sql oracle greatest-n-per-group

SQL脚本

select eventid_nbr, trunc(received_date, 'DD'), sentindicator, count(eventid_nbr) as count
from eventlog
where received_date between to_date('2017-07-01, 10:00 A.M.','YYYY-MM-DD, HH:MI A.M.') and to_date('2017-07-01, 11:00 A.M.','YYYY-MM-DD, HH:MI A.M.')
group by eventid_nbr, trunc(received_date, 'DD'), sentindicator
order by count desc, trunc(received_date, 'DD');

有输出

EVENT  RECEIVED_DATE  SENTINDICATOR   COUNT

1      01-JUL-17      Y               128
1      01-JUL-17      E1              2
104    01-JUL-17      Y               55
105    01-JUL-17      Y               4
106    01-JUL-17      Y               3

我需要在每个事件中选择的最大计数,其中输出将显示为

 EVENT  RECEIVED_DATE  SENTINDICATOR   COUNT

 1      01-JUL-17      Y           128
 104    01-JUL-17      Y           55
 105    01-JUL-17      Y           4
 106    01-JUL-17      Y           3

对于每个分组,我需要选择max(count)吗?我怎么能做到这一点?

1 个答案:

答案 0 :(得分:0)

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

select eventid_nbr, trunc(received_date, 'DD'), sentindicator, 
       count(eventid_nbr) as count
from eventlog
where received_date between to_date('2017-07-01, 10:00 A.M.','YYYY-MM-DD, HH:MI A.M.') and
                            to_date('2017-07-01, 11:00 A.M.','YYYY-MM-DD, HH:MI A.M.')
group by eventid_nbr, trunc(received_date, 'DD'), sentindicator
order by count desc, trunc(received_date, 'DD')
fetch first 1 row only;

在早期版本中,子查询执行相同的操作:

select el.*
from (select eventid_nbr, trunc(received_date, 'DD'), sentindicator, 
             count(eventid_nbr) as count
      from eventlog
      where received_date between to_date('2017-07-01, 10:00 A.M.','YYYY-MM-DD, HH:MI A.M.') and
                                  to_date('2017-07-01, 11:00 A.M.','YYYY-MM-DD, HH:MI A.M.')
      group by eventid_nbr, trunc(received_date, 'DD'), sentindicator
      order by count desc, trunc(received_date, 'DD')
     ) el
where rownum = 1;