Sometimes we need to obtain a cumulative sum of a columns in a query. How we can do it?
Suppose you have this simple table
id|in|out
----------
1 5 0
2 0 6
3 2 0
4 3 0
5 0 4
and you want obtain the cumulative sum of the column (in+out) like this
id|in|out|sum
-------------
1 5 0 5
2 0 6 11
3 2 0 13
4 3 0 16
5 0 4 20
This following query to do this
SELECT a.id, a.in, a.out,
Suppose you have this simple table
id|in|out
----------
1 5 0
2 0 6
3 2 0
4 3 0
5 0 4
and you want obtain the cumulative sum of the column (in+out) like this
id|in|out|sum
-------------
1 5 0 5
2 0 6 11
3 2 0 13
4 3 0 16
5 0 4 20
This following query to do this
SELECT a.id, a.in, a.out,
-- this is the new column called sum
( SELECT SUM( in + out )
FROM mytable b
WHERE b.id <= a.id
( SELECT SUM( in + out )
FROM mytable b
WHERE b.id <= a.id
) AS sum
FROM mytable a
ORDER BY id
ORDER BY id
Comments
Post a Comment