【发布时间】:2022-10-14 15:20:30
【问题描述】:
假设我有下表:http://sqlfiddle.com/#!17/3de963/1
我要计算的是表中每个付费月,我想计算该月和前 11 个月的总用户和总购买量(所以总共 12 个月,包括当前行的月份)。
我可以很容易地计算出总金额,我通过以下方式做到了这一点:
sum(purchase_amt) over (order by paidmonth asc rows 11 preceding)
但是,当我尝试这样做时:
count(distinct user_id) over (order by paidmonth asc rows 11 preceding)
我收到此错误:
如果指定了 DISTINCT,则不允许窗口 ORDER BY
所以这是我希望得到的结果:
| paidmonth | total_unique_users | total_amount | | ---------- | ------------------ | ------------ | | 2020-10-01 | 1 | 20 | | 2020-11-01 | 1 | 50 | | 2020-12-01 | 1 | 100 | | 2021-06-01 | 2 | 180 | | 2022-03-01 | 2 | 85 | | 2022-06-01 | 1 | 105 | | 2022-10-01 | 2 | 175 |如果您需要任何其他列,请告诉我,我会提供帮助。我在链接中显示的表格是 CTE 汇总表。
【问题讨论】:
-
Postgres 还是 BigQuery?请不要为不涉及的数据库添加标签
-
我认为 sqlfiddle 中的示例数据与您在此处的预期输出之间存在一些不一致。在任何情况下,使用
group by试试这个:select paidmonth, count(distinct user_id) unique_users, sum(purchase_amt) total_purchase_amt from test group by paidmonth order by paidmonth desc limit 12;
标签: sql postgresql google-bigquery