简体   繁体   中英

query for total column in every rows

I couldn't find right query solution to add total column for every row

table

+-----+---------+
|id   |amount   |
+-----+---------+
|1    |1000     |
+-----+---------+
|2    |2050     |
+-----+---------+
|3    |2666     |
+-----+---------+

needed result

+-----+---------+---------+
|id   |amount   |total    |
+-----+---------+---------+
|1    |1000     |1000     |
+-----+---------+---------+
|2    |2050     |3050     |
+-----+---------+---------+
|3    |2666     |5716     |
+-----+---------+---------+

ps: amount could be +/-

thanks

SELECT
  *
  ,(@runningtotal:= @runningtotal + t.amount) as RunningTotal
FROM
  TableName t
  CROSS JOIN (SELECT @runningtotal:= 0) var

Yep with a variable you can do it without a sub query. Here is a SQL fiddle of the example. http://sqlfiddle.com/#!9/956a2c/2

You are looking for a running sum. One way to do it in MySQL is with a correlated sub-query.

select id,amount,
amount+coalesce((select sum(amount) from tablename where id<t.id), 0) total
from tablename t

SQL Fiddle

You can try this:

SELECT aa.id, aa.amount,
    (
        SELECT SUM(amount)
        FROM your_table
        WHERE id <= aa.id
    ) AS total
FROM your_table AS aa

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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