给定下表:
CREATE TABLE cnts(
user_id INT,
month_d DATE,
cnt INT
)
我想查询每个 (user_id, month_d) 对的最后 6 个月的累积计数。我可以通过以下 JOIN 来做到这一点:
SELECT
S1.month_d AS "month_d",
S1.user_id AS "user_id",
SUM(S2.cnt) AS "last_6_months_cnt"
FROM cnts S1
LEFT JOIN cnts S2 ON S1.user_id = S2.user_id
AND (S2.month_d BETWEEN (S1.month_d - INTERVAL '5 MONTH') AND S1.month_d)
GROUP BY 1, 2
ORDER BY 2, 1;
但我想知道这是否可以用窗口函数解决?
样本数据:
INSERT INTO cnts(user_id, month_d, cnt) VALUES
(1, '2013-01-01', 2),
(1, '2013-04-01', 2),
(1, '2013-07-01', 2),
(1, '2013-10-01', 2),
(2, '2013-01-01', 2),
(2, '2013-04-01', 2),
(2, '2013-07-01', 2),
(2, '2013-10-01', 2)
;
预期结果(来自上面的连接):
month_d | user_id | last_6_months_cnt
------------+---------+-------------------
2013-01-01 | 1 | 2
2013-04-01 | 1 | 4
2013-07-01 | 1 | 4
2013-10-01 | 1 | 4
2013-01-01 | 2 | 2
2013-04-01 | 2 | 4
2013-07-01 | 2 | 4
2013-10-01 | 2 | 4