【问题标题】:How to select rows which has cumulative sum of column value min to given value如何选择列值 min 到给定值的累积总和的行
【发布时间】:2021-06-30 09:44:57
【问题描述】:

我需要从 PostgreSQL 中获取数据,我需要在以下条件下选择行。

id  type  total_quantity created_dttm [desc]
1    1    10            30-Jun-2021
2    1    12            27-Jun-2021
3    1    32            26-Jun-2021
4    1    52            25-Jun-2021

需要在查询和类型中获取与给定值匹配的所有行 [total_quantity 列值的总和]。如果我将值设为 24 并键入 1,那么我需要获取所有行 [total_quantity 值的累积值]

id  type  total_quantity created_dttm [desc]

1    1    10         30-Jun-2021  [10 less than 24 ] fetch row
2    1    12         27-Jun-2021  [22 (sum of current row &previous) less than 24]fetch row
3    1    32         26-Jun-2021  [54 [10+12+32]greater than 24] when greater than reached; 
                                  then fetch this row only
4    1    52         25-Jun-2021   [query should not fetch this row, since max reached @ id 3]

我尝试了两列的总和,但这不起作用,因为我正在寻找值范围之间的行,并且有条件选择所有小于给定值的行+选择给定值的下一个最大值..给定类型...

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    我们可以在这里使用SUM作为解析函数:

    WITH cte AS (
        SELECT *, SUM(total_quantity) OVER (ORDER BY created_dttm DESC)
                      - total_quantity AS tq_sum
        FROM yourTable
    )
    
    SELECT id, type, total_quantity, created_dttm
    FROM cte
    WHERE tq_sum < 24;
    

    Demo

    上述技巧(在 CTE 中)通过将当前行的总数从运行总数中保留下来。因此,超过阈值 24 的第一行也将被包括在内,因为它的总数将被排除在运行总数之外。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-31
      • 2021-03-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多