all groups > sql server programming > november 2007 >
You're in the

sql server programming

group:

summation of current and previous column???


summation of current and previous column??? perspolis
11/3/2007 12:00:00 AM
sql server programming: Hi all
I have a table like this
Code Value
1 1000
2 2000
3 -500
I want to write a query that returns like following output:
Code Value Total
1 1000 1000
2 2000 3000
3 -500 2500
I mean I want to sum a column with previous column..
how can I do that?
thanks in advance

Re: summation of current and previous column??? perspolis
11/3/2007 12:00:00 AM
thanks.
[quoted text, click to view]

Re: summation of current and previous column??? Dan Guzman
11/3/2007 7:55:27 AM
[quoted text, click to view]

One method to calculate a running total is with a subquery:

CREATE TABLE dbo.MyTable
(
[Code] int NOT NULL
CONSTRAINT PK_MyTable PRIMARY KEY,
[Value] int NOT NULL
)
INSERT INTO dbo.MyTable
SELECT 1, 1000
UNION ALL SELECT 2, 2000
UNION ALL SELECT 3, -500
GO

SELECT
[Code],
[Value],
(
SELECT SUM(Value)
FROM dbo.MyTable prev
WHERE
prev.[Code] <= curr.[Code]
) AS Total
FROM dbo.MyTable curr
ORDER BY [Code]

--
Hope this helps.

Dan Guzman
SQL Server MVP

[quoted text, click to view]
AddThis Social Bookmark Button