使用多个日期范围对数据进行计数


14

可能以前有人问过这个问题,但我无法弄清楚。我有一张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);

该表包含多个行业ID和日期的电话点击事件计数。

是否可以将具有多个日期范围的所有可用行业ID的这些点击计为条件?我想要这样的输出:

------------------------------------------------
industry_id |  today | yesterday | last 3 days |
------------------------------------------------
1           |  19    | 12        | 46          |
------------------------------------------------
2           |  35    | 0         | 42          |
------------------------------------------------
3           |  0     | 4         | 4           |
------------------------------------------------
4           |  0     | 22        | 22          |
------------------------------------------------

我试过按日期对分区进行计数,但是没有结果。是否可以在一个查询中选择此数据?额外的好处是可以指定日期范围内的前几个月:今天,昨天,3月,2月,1月等

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

我使用的是PostgreSQL 9.3,但欢迎使用9.4解决方案,因为我们会尽快迁移到它。

Answers:


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

在您的SQLFiddle中看到它。


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 ;

SQLfiddle中尝试过。


看起来好多了,过滤器是很棒的语法糖!该查询假定date是类型为datenot 的列timestamp。这种假设有时使我
不寒而栗

1
@Andomar,是的,我通常在日期/日期时间/时间戳查询中有开闭范围。数据类型的更改更难被咬住。
ypercubeᵀᴹ
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.