SQL查询根据移动日期窗口有条件地求和

时间:2010-01-11 22:38:08

标签: sql postgresql case

我正试图弄清楚我的用户的一些滑动窗口统计信息。我有一个包含用户的表,以及created_at和verified_at等列。对于每个月,我想知道注册了多少用户(由created_at的date_trunc创建的一个简单组),然后是那些人,在我的滑动窗口中验证了多少(称为60天)。

我想做一个SQL查询,它给我一些类似的东西:

Month    | Registered | Verified in 60 days
Jan 2009 | 1543       | 107
Feb 2009 | 2000       | 250

我正在使用postgresql。我开始看sum(case ...),但我不知道是否可以让我的情况以某种方式依赖于date_trunc。

当然,这不起作用,但这里的想法是:

SELECT DATE_TRUNC('month', created_at) as month, 
COUNT(*) as registered,
SUM(CASE WHEN verified_at < month+60 THEN 1 ELSE 0 END) as verified
FROM users
GROUP BY DATE_TRUNC('month', created_at)

3 个答案:

答案 0 :(得分:25)

SELECT  COUNT(created_at) AS registered,
        SUM(CASE WHEN verified_at <= created_at + '60 day'::INTERVAL THEN 1 ELSE 0 END) AS verified
FROM    generate_series(1, 20) s
LEFT JOIN
        users
ON      created_at >= '2009-01-01'::datetime + (s || ' month')::interval
        AND created_at < '2009-01-01'::datetime + (s + 1 || ' month')::interval
GROUP BY
        s

答案 1 :(得分:0)

也许你可以在不同月份结合在一起。

select sum(whatever), 'january' from user where month = 'january'
union all
select sum(whatever), 'february' from user where month = 'february'
...

答案 2 :(得分:0)

SELECT
    MONTH,
    COUNT(*) AS Registered,
    SUM (CASE WHEN datediff(day,reg_date,ver_date) < 60 THEN 1 ELSE 0) as 'Verified in 60 //days datediff is an MSSQL function amend for postgresql'
FROM
    TABLE
GROUP BY
    MONTH