使用多个日期范围计算数据

Val*_*n V 14 postgresql

可能以前有人问过这个问题,但我无法弄清楚。我有一张phone_clicks桌子(sql fiddle http://sqlfiddle.com/#!15/855e0/1

CREATE TABLE phone_clicks (
    id integer NOT NULL,
    date date NOT NULL,
    industry_id integer NOT NULL,
    clicks integer DEFAULT 0 NOT NULL
);

insert into phone_clicks(id, date, industry_id, clicks)
values
(1, '2015-03-16', 1, 15),
(2, '2015-03-16', 2, 7),
(3, '2015-03-16', 3, 0),
(4, '2015-03-17', 1, 12),
(5, '2015-03-17', 3, 4),
(6, '2015-03-17', 4, 22),
(7, '2015-03-18', 1, 19),
(8, '2015-03-18', 2, 35);
Run Code Online (Sandbox Code Playgroud)

此表包含多个industry_ids 和日期的电话点击事件计数。

是否可以以多个日期范围为条件计算所有可用industry_ids的这些点击次数?我想要这个输出:

------------------------------------------------
industry_id |  today | yesterday | last 3 days |
------------------------------------------------
1           |  19    | 12        | 46          |
------------------------------------------------
2           |  35    | 0         | 42          |
------------------------------------------------
3           |  0     | 4         | 4           |
------------------------------------------------
4           |  0     | 22        | 22          |
------------------------------------------------
Run Code Online (Sandbox Code Playgroud)

我试过使用按日期分区计数,但一无所获。是否可以在一次查询中选择此数据?额外的好处是能够将前几个月指定为日期范围:今天、昨天、三月、二月、一月等

更新:我已经更新了小提琴来定义当前月份、前几个月和上个月之前的日期范围。SQL 小提琴:http ://sqlfiddle.com/#!15/855e0/ 46

我正在使用 PostgreSQL 9.3,但欢迎使用 9.4 解决方案,因为我们很快就会迁移到它。

And*_*mar 8

select  industry_id
,       sum(case when current_date <= date then clicks end) as today 
,       sum(case when current_date-1 <= date and
                      date < current_date then clicks end) as yesterday
,       sum(case when current_date-4 <= date and 
                      date < current_date-1 then clicks end) as last3days
from    phone_clicks
group by
        industry_id
Run Code Online (Sandbox Code Playgroud)

在您的 SQLFiddle 中查看它。


ype*_*eᵀᴹ 7

在 9.4 版本中,我们将能够使用FILTER子句:

select  
    t.industry_id,
    sum(t.clicks) filter (where t.date = current_date) 
        as today,
    sum(t.clicks) filter (where t.date = current_date - interval '1 day')
        as yesterday,
    sum(t.clicks) filter (where t.date >= current_date - interval '2 days'
                            and t.date <= current_date) 
        as last_3_days
from 
    phone_clicks as t
group by 
    t.industry_id ;
Run Code Online (Sandbox Code Playgroud)

SQLfiddle 中尝试过。