Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
Friends,Please find my sample dataBillNo ItemNumber GrossAmnt1001 1 1001001 2 501001 3 2501002 1 751002 2 501003 1 230I will pass BillNo and ItemNumber as parameter and my Expected output will be,@BillNo = 1001 , ItemNumber = 2BillNo CurrentAmount TotalUptoPrevious Total1001 50 100 150@BillNo = 1001 , ItemNumber = 1BillNo CurrentAmount TotalUptoPrevious Total1001 50 0 50@BillNo = 1001 , ItemNumber = 3BillNo CurrentAmount TotalUptoPrevious Total1001 250 150 400@BillNo = 1003 , ItemNumber = 1BillNo CurrentAmount TotalUptoPrevious Total1003 230 0 230Could you please help me to get my expected output, Thanks in advance
sunitabeck
Master Smack Fu Yak Hacker
5155 Posts
Posted - 2011-05-26 : 13:01:20
A way of doing it:
SELECT a.BillNo, a.GrossAmt AS CurrentAmt, b.Total - a.GrossAmt AS TotalUptoPrevious, b.TotalFROM YourTable a CROSS APPLY ( SELECT SUM(GrossAmt) AS Total FROM YourTable b WHERE b.BillNo = a.BillNo AND b.ItemNumber <= a.ItemNumber ) bWHERE a.ItemNumber = @ItemNumber AND a.BillNumber = @BillNumber