英文:
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.
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论