如何从底部到顶部添加累积总和?

huangapple go评论60阅读模式
英文:

How can add the cumulative sum from bottom to top?

问题

创建一个临时表,并从顶部到底部添加num列:

WITH data (num) AS (
  VALUES(1),
        (5),
        (3)
)
SELECT num, sum(num) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data;

所有的num相加:

 num | sum 
-----+-----
   1 |   1
   5 |   6
   3 |   9

如何将所有的num从底部到顶部相加,如下:

 num | sum 
-----+-----
   1 |   9
   5 |   8
   3 |   3
英文:

Create a tmp table and add the num column from top till bottom::

WITH data (num) AS (
  VALUES( 1),
        ( 5),
        ( 3)
)
SELECT num, sum(num) OVER (ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data;

All the num added:

 num | sum 
-----+-----
   1 |   1
   5 |   6
   3 |   9

How can add all the num from bottom till top such as:

 num | sum 
-----+-----
   1 |   9
   5 |   8
   3 |   3

答案1

得分: 1

First of all, there needs to be a second column which provides the ordering you seem to think exists in your table. Note that SQL tables are based on unordered sets of tuples.

<!-- language: sql -->

WITH data (id, num) AS (
VALUES ROW(1, 1),
ROW(2, 5),
ROW(3, 3)
)

SELECT num, SUM(num) OVER (ORDER BY id DESC) AS sum
FROM data
ORDER BY id;

Here we are taking a rolling sum in the reverse order.

<h2>Demo</h2>

英文:

First of all, there needs to be a second column which provides the ordering you seem to think exists in your table. Note that SQL tables are based on unordered sets of tuples.

<!-- language: sql -->

WITH data (id, num) AS (
    VALUES ROW(1, 1),
           ROW(2, 5),
           ROW(3, 3)
)

SELECT num, SUM(num) OVER (ORDER BY id DESC) AS sum
FROM data
ORDER BY id;

Here we are taking a rolling sum in the reverse order.

<h2>Demo</h2>

huangapple
  • 本文由 发表于 2023年2月18日 13:38:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75491432.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定