2017-08-11 37 views
0

的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)?我怎么能做到这一点?

+0

我已经更新说明我的问题需要选择与事件1相同的包含重复项的所有事件(可能是200),并且只包含那些列COUNT为MAX(COUNT)的元组。对于非重复事件,例如104,105和106,它们的元组包含在结果集中,因此它们的计数已经是最大值(COUNT) – Mushy

回答

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; 
+0

您能否根据对问题的编辑进行更详细的阐述以进一步澄清? – Mushy

0
select eventid,dt,sentindicator,max(count) 
from 
(
    select eventid_nbr, trunc(received_date, 'DD') as dt, 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'))a 
group by eventid,dt,sentindicator 
+0

只需添加一个带有max(count)的外部查询作为查询的外部查询 – Aparna

0
select eventid_nbr, received_day, max(sentindicator) keep(dense_rank last order by count), max(count) as count 
from (select eventid_nbr, trunc(received_date, 'DD') as received_day, sentindicator, count(*) 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) 
group by eventid_nbr, received_day 
order by 4 desc, received_day;