Cannot get correct count

时间:2018-03-25 19:14:26

标签: sql oracle

I want to total the unique package id's in the following query, but when I run this it will show me just 1 for each row regardless if the package id occurs more than once. Is there something I am not doing correctly?

select 
trans.package_id, 
trans.destination, 
trans.date_time, 
count(trans.package_id) as count 
from
    (select 
    pl.package_id, 
    pl.destination, 
    to_char(pl.tran_date,'MM/DD/YY-HH:MI:SS') as date_time 
    from package_log pl
    where pl.destination in 
    ('MRAUD-08','MRAUD-09','MRAUD-10','MRAUD-11','MRAUD-12','MRAUD-13','MRAUD-14','MRAUD-15','MRAUD-16') 
    union all
    select 
    pl.package_id, 
    pl.destination, 
    to_char(pl.tran_date,'MM/DD/YY-HH:MI:SS') as date_time 
    from package_log pl
    where pl.destination 
    in ('MROC-01','MROC-01','MROC-02','MROC-03','MROC-03','MROC-04','MROC-05','MROC-06','MROC-07','MROC-08','MROC-09','MROC-10','MROC-11','MROC-12','MROC-13','MROC-14','MROC-15','MROC-16','MROC-17','MROC-18','MROC-19','MROC-20')
    and pl.source in
    ('MRAUD-08','MRAUD-09','MRAUD-10','MRAUD-11','MRAUD-12','MRAUD-13','MRAUD-14','MRAUD-15','MRAUD-16')
    union all
    select 
    pl.package_id, 
    pl.destination, 
    to_char(pl.tran_date,'MM/DD/YY-HH:MI:SS') as date_time 
    from package_log pl
    where pl.source
    in ('MROC-01','MROC-01','MROC-02','MROC-03','MROC-03','MROC-04','MROC-05','MROC-06','MROC-07','MROC-08','MROC-09','MROC-10','MROC-11','MROC-12','MROC-13','MROC-14','MROC-15','MROC-16','MROC-17','MROC-18','MROC-19','MROC-20')
    ) trans
group by 
trans.package_id, trans.destination, trans.date_time
order by 
trans.package_id, trans.date_time;

I need it look like:

11325   MRAC-10 07/12/17-08:20:44   1
11403   MRE-18-1 07/12/17-06:55:45  1
11404   MRC-17  07/11/17-06:40:08   1
11407   MRC-18  07/12/17-07:04:33   1
11411   MRD-18  07/13/17-06:21:22   2
11411   MRD-18  07/15/17-05:34:28   2

1 个答案:

答案 0 :(得分:1)

Seems you want a Windowed Aggregate:

select 
   trans.package_id, 
   trans.destination, 
   trans.date_time, 
   count(trans.package_id) 
   over (partition by trans.package_id, trans.destination) as count 
   -- maybe
   -- over (partition by trans.package_id) as count
from
    (select 
...
    ) trans
-- no Group By
order by 
   trans.package_id, trans.date_time;