Postgresql - 窗口函数聚合

时间:2017-06-07 02:43:10

标签: sql postgresql aggregate-functions window-functions

我正在尝试按产品类型查找每月新用户的数量。但是,我继续收到错误请求cnt在聚合函数中使用。

SELECT EXTRACT(MONTH FROM date) AS month
FROM (SELECT users.date,
             COUNT(*) OVER(PARTITION BY product_type) AS cnt FROM users) AS u
GROUP BY month
ORDER BY cnt DESC;

1 个答案:

答案 0 :(得分:0)

这似乎是一个非常奇怪的结构。这是一种不使用窗口函数的方法:

select date_trunc('month', date) as  yyyymm, product_id, count(*)
from (select distinct on (u.userid) u.*
      from users u
      order by u.userid, u.date
     ) u
group by date_trunc('month', date), product_id
order by yyyymm, product_id;