简体   繁体   English

以特定方式汇总一列中的值

[英]Summing up values in one column in specific way

So i have aa simple table: 所以我有一个简单的表:

id     amount
 1.      40
 2.      50
 3.      60

I would like to create a query that will return an id number with the sum in a way that first id will have sum 40 , second id will have 40+50=90 , third 40+50+60= 150. Visualized output would be something like this: 我想创建一个查询,它将以一个第一个id将具有总和40的方式返回一个id号,第二个id将具有40 + 50 = 90,第三个40 + 50 + 60 = 150.可视化输出将是这样的事情:

id    sum
1.     40
2.     90
3.    150

You can use a correlated subquery : 您可以使用相关子查询:

select t.*,
       (select sum(t1.amount) from table t1 where t1.id <= t.id) as sum
from table t;

If you are working with latest version then you can do : 如果您使用的是最新版本,则可以执行以下操作:

select t.*,
       sum(amount) over (order by id)
from table t;

Here is a MySQL 8+ option: 这是一个MySQL 8+选项:

SELECT
    id,
    SUM(amount) OVER (ORDER BY id) sum
FROM yourTable;

Demo 演示

This is probably the most performant way to write your query. 这可能是编写查询的最高性能方式。 If you happen to be using an earlier version of MySQL, then use a correlated subquery: 如果您碰巧使用早期版本的MySQL,则使用相关子查询:

SELECT
    id,
    (SELECT SUM(t2.amount) FROM yourTable t2 WHERE t2.id <= t1.id) AS sum
FROM yourTable t1;

它很简单......

SELECT id, SUM(amount) OVER (ORDER BY id) sum FROM TableName

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM