【问题标题】:SQL - How to get the sum of 3 leading values greater than the current value in a different columnSQL - 如何获得大于不同列中当前值的 3 个前导值的总和
【发布时间】:2021-08-26 06:00:36
【问题描述】:

我有一个数据表,如下所示

我想要的输出在最后一列中,它本质上是大于当前值的月份差异的 sum(value for next 3 leading value),即第一行中的值 33sum(Value) for month_diff>0 i.e. 1-3,类似地,第 7 行 22 是 @ 987654327@。以此类推。

它必须按 id 列进行分区

【问题讨论】:

    标签: sql google-bigquery


    【解决方案1】:

    根据您的描述,您需要一个窗框规格:

    select t.*,
           sum(value) over (partition by id1, id2
                            order by month_diff
                            rows between 1 following and 3 following
                           ) as desired_output
    from t;
    

    如果你想确定你实际上有三个值,那么你需要一些case 逻辑:

    select t.*,
           (case when lead(id1, 3) over (partition by id1, id2 order by month_diff) is not null
                 then sum(value) over (partition by id1, id2
                                       order by month_diff
                                       rows between 1 following and 3 following
                                      )
            end) as desired_output
    from t;
    

    【讨论】:

      【解决方案2】:

      考虑以下方法

      select *, 
        if(count(*) over win = 3, sum(value) over win, 0) output
      from `project.dataset.tabel`
      window win as (
        partition by id1, id2 
        order by month_diff 
        rows between 1 following and 3 following
      )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-11-30
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多