简体   繁体   中英

how to count aggregate distinct IDs Per Hour Since Beginning of the day?

I need to write a Query, which count distinct IDs and aggregate them over time.

for example

在此处输入图像描述

and the result should be

在此处输入图像描述

For each id , record the first time the id shows up and then do a cumulative sum:

select hour, sum(count(*)) over (partition by day order by hour)
from (select day, id, min(hour) as hour
      from t
      group by day, id
     ) t
group by hour
order by hour;

Note: This assumes that you really want hour within a given day.

You can also express this as:

select day, hour, sum(cnt) over (partition by day order by hour)
from (select day, hour, count(*) as cnt
      from (select day, id, min(hour) as hour
            from t
            group by day, id
           ) t
      group by hour
     ) h
order by hour;

The above will not include an hour unless there is an new id in that hour. For all hours, you can use window functions instead:

select hour,
       sum(sum( (seqnum = 1)::int ) over (partition by day order by hour)
from (select day, id,
             row_number() over (partition by day, id order by hour) as seqnum
      from t
     ) t
group by hour
order by hour;

You can also express this as:

select day, hour, sum(cnt) over (partition by day order by hour)
from (select day, hour, sum( (seqnum = 1)::int ) as cnt
      from (select day, id,
                   row_number() over (partition by day, id order by hour) as seqnum
            from t
           ) t
      group by hour, day
     ) dh
order by hour;

I had a different count per hour.

declare @tmp as table(RecordNumber int, Day date, Hour int, ID int)
insert into @tmp(RecordNumber,Day,Hour,ID) values(1,'4/27/2021',1,100),
(2,'4/27/2021',1,100)
,(3,'4/27/2021',1,101)
,(4,'4/27/2021',2,202)
,(5,'4/27/2021',2,203)
,(6,'4/27/2021',3,101)
,(7,'4/27/2021',8,305)
,(8,'4/27/2021',16,100)
,(9,'4/27/2021',22,30)
,(10,'4/27/2021',22,1000)
,(11,'4/27/2021',23,100)
,(12,'4/27/2021',23,50)


select distinct Day, Hour, count(distinct ID) ID_Count from @tmp
group by Day, Hour

output

 Hour   ID_Count
   1    2
   2    2
   3    1
   8    1
  16    1
  22    2
  23    2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM