【问题标题】:Updating cumulative sum ordered by two columns更新按两列排序的累积和
【发布时间】:2012-12-25 15:21:43
【问题描述】:

给定表格:

id   date count cumulative_sum
1    2    100                  
2    1    50
3    1    10
4    2    5

如何更新由dateid 排序的行的cumulative_sum

结果应该是:

id   date count cumulative_sum
2    1    50    50
3    1    10    60
1    2    100   160
4    2    5     165

是否也可以只更新插入或更新行时需要重新计算的那些行?

【问题讨论】:

    标签: sql sqlite cumulative-sum


    【解决方案1】:

    你可以用这个:

    update your_table
    set
      cumulative_sum = (select sum(c)
                        from your_table t2
                        where
                          t2.date<your_table.date
                          or (t2.date=your_table.date
                              and t2.id<=your_table.id));
    

    子查询统计count的累计总和,即日期为

    你也可以这样写:

    where cumulative_sum is null
    

    仅当还没有值时才更新行。如果插入到表中的所有 id 和日期始终按升序排列,这将起作用。

    【讨论】:

      【解决方案2】:

      首先按所需顺序对表进行排序,然后使用下面的查询将其放入#temp

      Declare @count int=0
      
      UPdate #temp Set @count = cumulative_sum =  count + @count
      

      【讨论】:

        【解决方案3】:

        date 列使用ORDER BY 函数。

        SELECT * FROM yourTableName ORDER BY date

        【讨论】:

          猜你喜欢
          • 2018-03-02
          • 2022-08-18
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-03-13
          • 1970-01-01
          • 2019-10-05
          • 1970-01-01
          相关资源
          最近更新 更多