SQL Server Forums
Profile | Register | Active Topics | Members | Search | Forum FAQ
 
Register Now and get your question answered!
Username:
Password:
Save Password
Forgot your Password?

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 sql query
 New Topic  Reply to Topic
 Printer Friendly
Author Previous Topic Topic Next Topic  

aj007
Starting Member

1 Posts

Posted - 08/11/2012 :  05:10:53  Show Profile  Reply with Quote
Hello,

I have one scenario that i'm working on and it is like this

Table look like this

Field1 Field2 Field3 Sum
1 2 3 6
2 3 4 9
3 1 3 7


The output i'm specifically lookin' for is like this

Field1 Field2 Field3 Sum
1 2 3 6
6 3 4 13
13 1 3 17


so the sum in the previous row should be the value in Field1 for the subsequent row.The value in Field1 for the first row would remain unchanged.

Please help me with my query.

Thanks,
AJ

Edited by - aj007 on 08/11/2012 05:15:51

sunitabeck
Flowing Fount of Yak Knowledge

5152 Posts

Posted - 08/11/2012 :  08:25:44  Show Profile  Reply with Quote
How do you decide the ordering of the rows? In a SQL, by definition, rows in a table form an unordered collection. So you have to have some way of ordering the data to do the computations that you described. The ordering could be based on some of the existing columns, or may be you have another column that determines the sorting order.

Edited by - sunitabeck on 08/11/2012 08:26:24
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

India
47189 Posts

Posted - 08/11/2012 :  10:30:46  Show Profile  Reply with Quote
for the sample data it looks like this

;With CTE
AS
(
SELECT Field1,Field2,Field3,Field1 + Field2+ Field3 AS Total,
ROW_NUMBER() OVER (ORDER BY Field1) AS Seq
FROM Table
)

SELECT COALESCE(c2.Total,c1.Field1),c1.Field2,c1.field3,COALESCE(c2.Total,c1.Field1)+ c1.Field2 + c1.Field3 AS [Sum]
FROM CTE c1
LEFT JOIN CTE c2
ON c2.Seq= c1.Seq-1


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
  Previous Topic Topic Next Topic  
 New Topic  Reply to Topic
 Printer Friendly
Jump To:
SQL Server Forums © 2000-2009 SQLTeam Publishing, LLC Go To Top Of Page
This page was generated in 0.06 seconds. Powered By: Snitz Forums 2000