如何计算从一天开始每小时聚合的不同ID?

yquaqz18  于 2021-07-26  发布在  Java
关注(0)|答案(2)|浏览(373)

我需要编写一个查询,对不同的id进行计数并随着时间的推移进行聚合。
例如

结果应该是

sz81bmfz

sz81bmfz1#

对于每个 id ,记录id第一次出现的时间,然后进行累加:

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;

注意:这假设您真的希望在给定的一天内有一个小时。
也可以表示为:

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;

以上不包括一小时,除非该小时内有新的id。对于所有时间,您都可以改用窗口功能:

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;

也可以表示为:

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;
mrzz3bfm

mrzz3bfm2#

我每小时有不同的计数。

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

输出

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

相关问题