【问题标题】:Cumulated Cohorts in SQLSQL 中的累积队列
【发布时间】:2021-09-27 03:50:40
【问题描述】:

我有下表:

cohort month cohort orders cumulated orders
2021-01 0 126 126
2021-01 1 5 131
2021-01 2 4 135
2021-02 0 131 131
2021-02 1 9 140
2021-02 2 8 148

现在我想要下表,其中我将每个重复订单除以第 0 个月的订单数:

cohort month cohort orders cumulated orders cumulated in %
2021-01 0 126 126 100%
2021-01 1 5 131 104%
2021-01 2 4 135 107%
2021-02 0 131 131 100%
2021-02 1 9 140 107%
2021-02 2 8 148 114%

我唯一的提示是创建一个 CASE 语句,但我不希望每个月都通过添加行来更新查询

WHEN cohort="2021-08" THEN cumulated orders / 143

其中 143 是队列 2021-08 月队列 =0 的订单数

有人知道如何获得这张桌子吗?

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    不需要case 表达式。你可以使用first_value():

    select t.*,
           ( cumulated_order /
             first_value(orders) over (partition by cohort order by month_cohort)
           ) as ratio
    from t;
    

    如果你真的想要case,你可以使用:

    select t.*,
           ( cumulated_order /
             max(case when month_cohort = 0 then orders end) over (partition by cohort)
           ) as ratio
    from t;
    

    【讨论】:

      【解决方案2】:

      考虑下面

      select *, 
        round(100 * cumulated_orders / 
          sum(if(month_cohort = 0, orders, 0)) over(partition by cohort) 
        ) as cumulated_in_percent
      from `project.dataset.table`         
      

      如果应用于您问题中的样本数据 - 输出是

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-08
        • 2021-09-30
        • 2012-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多