【问题标题】:How to calculate a cumulative sum from the bottom up?如何自下而上计算累计和?
【发布时间】:2015-12-28 13:22:47
【问题描述】:

我在 PostgreSQL 中有一个查询结果:

itemorder   name    qty
  1          A       -20
  2          A2       350
  3          A        50
  4          A        -10
  5          A2       10

itemorder 列给出了我期望看到的正确的行顺序。 我需要从下到上传递行并计算一个初始值为100 的新列,并对A 的每一行执行+ qty

itemorder   name    qty       modifyed_sum
  1          A       -20          120       / 140 + (-20)
  2          A2       350         140       / not A
  3          A        50          140       / 90 + 50
  4          A        -10         90        / 100 +  (-10)
  5          A2       10          100       / not A

我该怎么做?

【问题讨论】:

  • 我觉得显示原始查询和示例数据可能会有所帮助。
  • 原始查询无关紧要,这就是它产生的结果。你可以使用'X'中的`我会知道如何转换它以从查询中提取数据。
  • 不。我们可能不需要像您那样使用原始查询。但无论如何@VR46 在创纪录的时间内舔了你的问题。
  • 您的 Postgres 版本丢失。

标签: sql postgresql


【解决方案1】:

试试这个

SELECT 100+ Sum(CASE WHEN name = 'a' THEN qty ELSE 0 END)OVER(ORDER BY itemorder DESC) as modifyed_sum,
       qty,
       name,
       itemorder
FROM   Yourtable
ORDER  BY itemorder ASC

另一种方式

SELECT 100 + (SELECT Sum(CASE WHEN b.name = 'a' THEN b.qty ELSE 0 END)
              FROM   yourtable  b
              WHERE  a.itemorder <= b.itemorder),
       qty,
       name,
       itemorder
FROM   yourtable a
ORDER  BY itemorder ASC

【讨论】:

  • 如何在查询中使用 IF?
  • @200_success - 是的,它是ASC
【解决方案2】:
SELECT itemorder
     , name
     , qty
     , 100 + SUM(CASE WHEN name = 'A' THEN qty ELSE 0 END)
             OVER (ORDER BY itemorder ASC ROWS BETWEEN CURRENT ROW AND UNBOUNDED FOLLOWING) AS modifyed_sum
    FROM thetable
    ORDER BY itemorder;

ROWS BETWEEN … 功能是 a value expression,用于 window function

【讨论】:

    猜你喜欢
    • 2017-02-23
    • 2021-05-11
    • 2014-02-16
    • 2017-03-06
    • 2020-06-17
    • 2021-10-24
    • 2016-05-11
    • 2019-08-23
    • 1970-01-01
    相关资源
    最近更新 更多