恐怕带有PARTITION BY user_id子句的窗口函数row_number()与您的情况无关,因为它只关注当前行的user_id,而您想要的是包含所有用户的合并视图。我没有比在表sales上执行自连接更好的主意了:
WITH list AS (
SELECT DISTINCT ON (s2.date, user_id)
s2.date
, product
FROM sales AS s1
INNER JOIN (SELECT DISTINCT date FROM sales) AS s2
ON s1.date <= s2.date
ORDER BY s2.date, user_id, s1.date DESC
)
SELECT date, product, count(*)
FROM list
GROUP BY date, product
ORDER BY date
1条答案
按热度按时间pgvzfuti1#
恐怕带有
PARTITION BY user_id
子句的窗口函数row_number()
与您的情况无关,因为它只关注当前行的user_id,而您想要的是包含所有用户的合并视图。我没有比在表sales
上执行自连接更好的主意了:请参见dbfiddle中的测试结果