基于周的活动枢纽

时间:2019-01-10 10:52:20

标签: sql postgresql

我的源表格式为:

event   start   end
event1  21/01/2019  15/02/2019
event2  01/01/2019  08/01/2019
event3  15/01/2019  13/02/2019
event4  07/01/2019  18/03/2019

我想要实现的是对一年中每个特定星期发生的事件的每周摘要。像这样:

week    events
1   1
2   2
3   2
4   3
...

由于我一无所知,因此非常感谢您提供有关如何执行此操作的任何提示。 我正在运行PostgreSQL 9.6。

2 个答案:

答案 0 :(得分:0)

您必须如下使用窗口函数:

select distinct w1.weeknum, 
    count(e1.id) over(partition by w1.weeknum) as eventqty
from (select generate_series(1, 52, 1) AS weeknum) w1
left join eventlog e1
on extract(week from startdate)<=w1.weeknum and extract(week from enddate)>=w1.weeknum

Here是有效的示例。

答案 1 :(得分:0)

首先,我提醒您不要将年份排除在计算之外。这样的日期范围通常会超出年份范围,因此您需要小心。

我认为进行这种计算的最有效方法是从日期算起“入”和“出”。这涉及拆分数据然后重新聚合。

查询如下:

with el as (
      select id,
             date_trunc('week', startdate) as wk,
             1 as inc
      from eventlog
      union all
      select id,
             date_trunc('week', enddate) + interval '1 week' as wk,
             -1 as inc
      from eventlog
     )
select wk,
       sum(inc) as week_net,
       sum(sum(inc)) over (order by wk) as active_in_week
from el
group by wk
order by wk;

Here是dbfiddle。