【问题标题】:How do I calculate unique users in each month but excluding the count of users if they were existing in 12 months prior?如何计算每个月的唯一用户数,但不包括 12 个月前存在的用户数?
【发布时间】: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


【解决方案1】:

诀窍是将您的用户列表转换为数组,然后进行取消嵌套的计算。希望这可以帮助。

with temp_table as (
  select '2020-10-01' paidmonth, 23 user_id, 392 order_id, 20 purchase_amt union all
  select '2020-11-01', 23, 406, 30 union all
  select '2020-12-01', 23, 412, 50 union all
  select '2021-06-01', 32, 467, 80 union all
  select '2022-03-01', 87, 449, 5 union all
  select '2022-06-01', 87, 512, 100 union all
  select '2022-10-01', 87, 553, 50 union all
  select '2022-10-01', 155, 583, 20
),
  calcs AS (
  SELECT
    paidmonth,
    purchase_amt,
    ARRAY_AGG(user_id) OVER(ORDER BY paidmonth ASC ROWS 11 PRECEDING ) AS last_11_unique_users
  FROM
    temp_table )
SELECT
  paidmonth,
  (SELECT COUNT(DISTINCT users) FROM UNNEST(last_11_unique_users) AS users) total_unique_users,
  SUM(purchase_amt) OVER (ORDER BY paidmonth ASC ROWS 11 PRECEDING) total_amount
FROM
  calcs

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-13
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2020-10-13
    • 1970-01-01
    • 2020-05-29
    • 1970-01-01
    相关资源
    最近更新 更多