我有一个表每15分钟计算一次用户数,然后在数据库中记录该数字。参赛作品如下所示:
users1| users2 |Time_Stamp
15 | 0 |2014-03-15 13:00:00.000
35 | 15 |2014-03-15 13:15:00.000
12 | 55 |2014-03-15 13:30:00.000
2 | 115 |2014-03-15 13:45:00.000
0 | 5 |2014-03-15 14:00:00.000
2 | 115 |2014-03-16 12:45:00.000
123 | 15 |2014-03-16 13:00:00.000
我需要做的是在特定时间内选择最大用户数(针对特定群组),在这种情况下,每天在午夜之间分组,然后显示甚至发生的确切时间。
在上面的例子中,我想要的输出是:
max users1 |Time_Stamp
35 |2014-03-15 13:15:00.000
123 |2014-03-16 13:00:00.000
每天最多可以获得最大值,并忽略时间戳。
select cast(time_stamp as date) as "time", max(users1) as "c"
from Counts
where users1 > 0
group by cast(time_stamp as date)
哪个给出了
max users1 |Time_Stamp
35 |2014-03-15
123 |2014-03-16
换句话说,我需要一天中的最大用户数以及发生的时间。
我已经解决了这个问题,但看起来非常可怕。以下是我的解决方案。有没有人可以帮我提出更好的方法?
此外,我希望不仅能够每天,而且每小时或每6小时完成这些读数。
select users1, TIME_STAMP
from counts c
inner join (
select
cast(abc.time as datetime) as "day_start",
dateadd(day,+1,cast(abc.time as datetime)) as "day_end",
abc.c as "day_max"
from (
select cast(time_stamp as date) as "time", max(users1) as "c"
from Counts
where users1 > 0
group by cast(time_stamp as date)
) abc
) t
on t.day_max = c.users1
where c.TIME_STAMP >= t.day_start
and c.TIME_STAMP < t.day_end
order by c.TIME_STAMP desc
编辑:有时,最大值不是唯一的。我希望能够在最大值出现时显示每个时间戳。
示例,然后预期输出,低于。
users1| TIME_STAMP
137 | 2014-06-21 11:15:00.000
137 | 2014-06-21 11:00:00.000
137 | 2014-06-21 10:45:00.000
137 | 2014-06-21 10:30:00.000
137 | 2014-06-21 10:15:00.000
136 | 2014-06-21 10:00:00.000
136 | 2014-06-21 09:45:00.000
136 | 2014-06-21 09:30:00.000
136 | 2014-06-21 09:15:00.000
136 | 2014-06-21 09:00:00.000
users1| TIME_STAMP
137 | 2014-06-21 11:15:00.000
137 | 2014-06-21 11:00:00.000
137 | 2014-06-21 10:45:00.000
137 | 2014-06-21 10:30:00.000
137 | 2014-06-21 10:15:00.000
答案 0 :(得分:1)
而不是group by
使用row_number()
:
select c.*
from (select c.*,
row_number() over (partition by cast(time_stamp as date) order by users1 desc) as seqnum
from counts c
) c
where seqnum = 1;
这将返回每天最大值的行。
编辑:
如果您希望所有行都有最大值,请使用rank()
或dense_rank()
代替row_number()
:
select c.*
from (select c.*,
dense_rank() over (partition by cast(time_stamp as date) order by users1 desc) as seqnum
from counts c
) c
where seqnum = 1;