如何计算SQL中时间范围的最大行数?

时间:2015-03-19 07:07:28

标签: sql postgresql

这是Postgresql中的表:

mydb=# \d login_log 
              Table "public.login_log"
   Column    |           Type           | Modifiers 
-------------+--------------------------+-----------
 id          | integer                  | 
 login_start | timestamp with time zone | 
 login_end   | timestamp with time zone | 

某些行:

1 | 2015-03-19 10:00:00  | 2015-03-19 13:30:00
2 | 2015-03-19 10:20:00  | 2015-03-19 13:20:00
3 | 2015-03-19 13:00:00  | 2015-03-19 16:00:00
4 | 2015-03-19 13:10:00  | 2015-03-19 16:00:00
5 | 2015-03-19 14:30:00  | 2015-03-19 15:30:00
6 | 2015-03-19 15:00:00  | 2015-03-19 15:30:00
7 | 2015-03-19 12:00:00  | 2015-03-19 18:00:00

我需要一个SQL来计算最大登录用户的时间范围。

通过上面的例子,结果是:

在时间范围内:2015-03-19 13:10:00 ~ 2015-03-19 13:20:00, 5位用户已登录。(1,2,3,4,7)

2 个答案:

答案 0 :(得分:2)

使用range types(构建它们"动态")。他们提供了很多有用的functions and operators。您只需要定义一个custom aggregate,它将为您提供整体交叉点。所以 - 你最终会得到这样的东西:

with common as (
  select (intersection(tsrange(login_start, login_end))) as period 
  from login_log 
)
select 
  -- common.period, 
  -- array_agg(id) 
  *
from common, login_log
WHERE tsrange(login_start, login_end) && common.period
-- GROUP BY common.period
/* 
for some reason, when uncommenting the "^--..." lines, 
and commenting the "*" one - sqlfiddle shows an empty result. 
Nevertheless it works on my local posgres...
*/ 

请参阅工作示例:http://sqlfiddle.com/#!15/0c9c6/10

答案 1 :(得分:0)

使用UNION ALL查找感兴趣的不同时间戳,计算这些时间戳的活跃用户数:

select ts,
       (select count(*) from login_log t2
        where timestamps.ts between t2.login_start and t2.login_end) as count
from (select login_start as ts
      from login_log
      union all
      select login_end
      from login_log) as timestamps
order by count desc
fetch first 1 row only

最后命令降序并仅选择最高值!

(来自非Postgresql用户,所以有些细节可能有误...如果是这样的话请评论,我会编辑!)