日期之间的条目数

时间:2016-03-20 21:40:06

标签: postgresql amazon-redshift

我有一个具有以下结构的表: -

day,        id
2016-03-13, 123
2016-03-13, 123
2016-03-13, 231
2016-03-14, 231
2016-03-14, 231
2016-03-15, 129

我想构建一个看起来像这样的表: -

id,   d1, d7, d14
123,  1,  1,  1
231,  1,  2,  2
129,  1,  1,  1

基本上对于给定的ID,列出在时间窗口内具有条目的天数。因此,如果id 123在过去14天内有10个条目 - d14将为10。

到目前为止,我有: -

    SELECT
        day,
        id
    FROM
        events
    WHERE
        datediff (DAY, day, getdate()) <= 7
    GROUP BY
        day,
        id

2 个答案:

答案 0 :(得分:1)

此查询将执行:

SELECT
    id,
    COUNT(DISTINCT CASE WHEN current_date - day <=  1 THEN 1 END) d1,
    COUNT(DISTINCT CASE WHEN current_date - day <=  7 THEN 1 END) d7,
    COUNT(DISTINCT CASE WHEN current_date - day <= 14 THEN 1 END) d14
FROM
    events
GROUP BY
    id
ORDER BY
    id

或者,从PostgreSQL 9.4开始,稍微简洁一点:

SELECT
    id,
    COUNT(DISTINCT day) FILTER (WHERE current_date - day <=  1) d1,
    COUNT(DISTINCT day) FILTER (WHERE current_date - day <=  7) d7,
    COUNT(DISTINCT day) FILTER (WHERE current_date - day <= 14) d14
FROM
    events
GROUP BY
    id
ORDER BY
    id

答案 1 :(得分:0)

试试这个:

SELECT id
, count(case when DAY = getdate() then 1 else null end) as d1
, count(case when DAY + 7 >= getdate() then 1 else null end) as d7
, count(case when DAY + 14 >= getdate() then 1 else null end) as d14
FROM events
WHERE DAY between DAY >= getdate() - 14 
--or if you can have day > today ...  and DAY between getdate() - 14 and getdate()
GROUP By id