postgresql 计算多个日期的窗口函数

zed5wv10  于 2022-11-04  发布在  PostgreSQL
关注(0)|答案(1)|浏览(130)

{"header":{"type":"auto_translation","ret_code":"NullPointerException","time_cost":3194.0,"request_id":"767f36245be611ed992e0cc72940db38"}}

pgvzfuti

pgvzfuti1#

恐怕带有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

请参见dbfiddle中的测试结果

相关问题