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.
| Author |
Topic |
|
jamie
Aged Yak Warrior
542 Posts |
Posted - 2009-01-22 : 09:05:16
|
| hi,I have fields in a table showing number of starting customers and number of leaving customers.This looks like Year Month Starting Leaving2006 1 10 22006 2 5 6How can I also add in the calcs for Opening and Closing balances ?so the table will look like :Year Month Open Starting Leaving Closing2006 1 0 10 2 82006 2 8 5 6 7The table is Select year(date1) as year, month(date1) as month, count(starters), count(leavers) from custs group by year(date1), month(date1) thank you for any help. |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-01-22 : 09:14:45
|
| [code];WIth CTE(Seq,Year, Month, Starting, Leaving)AS(SELECT ROW_NUMBER() OVER (ORDER BY Year,Month),Year,Month,Starting,LeavingFROM Table)SELECT c1.Year,c1.Month,COALESCE(c2.Open,0) AS Open,c1.Starting,c1.Leaving,COALESCE(c2.Open,0) + c1.Starting - c1.Leaving AS LeavingStarting-Leaving AS ClosingFROM CTE c1OUTER APPLY (SELECT TOP 1 Starting-Leaving AS Open FROM CTE WHERE Seq<c1.Seq ORDER BY Seq DESC)c2[/code] |
 |
|
|
jamie
Aged Yak Warrior
542 Posts |
Posted - 2009-01-22 : 09:42:51
|
| hi, Thank you, this looks like it is nearly working..my opening balane seems incorrect..should there be a comma between :COALESCE(c2.Open,0) + c1.Starting - c1.Leaving AS LeavingStarting-Leaving AS Closing?The first row is ok, but then doesn't seem to roll coreectly :2003 8 0 2 0 2 22005 1 2 1 0 3 12005 6 1 1 0 2 1 |
 |
|
|
jamie
Aged Yak Warrior
542 Posts |
Posted - 2009-01-22 : 10:09:37
|
| The opening needs to be the previous months closing.not sure how that will work ? |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-01-22 : 10:56:05
|
what about this?;WIth CTE(Seq,Year, Month, Starting, Leaving)AS(SELECT ROW_NUMBER() OVER (ORDER BY Year,Month),Year,Month,Starting,LeavingFROM Table)SELECT c1.Year,c1.Month,COALESCE(c2.Open,0) AS Open,c1.Starting,c1.Leaving,COALESCE(c2.Open,0) + c1.Starting - c1.Leaving AS LeavingStarting-Leaving AS ClosingFROM CTE c1OUTER APPLY (SELECT SUM(Starting)-SUM(Leaving) AS Open FROM CTE WHERE Seq<c1.Seq)c2 if this is still incorrect, please some sample data to show what you expect |
 |
|
|
jamie
Aged Yak Warrior
542 Posts |
Posted - 2009-01-22 : 11:02:08
|
| Thank you so much ! that works perfectly.what would we do without you ! |
 |
|
|
visakh16
Very Important crosS Applying yaK Herder
52326 Posts |
Posted - 2009-01-22 : 11:07:44
|
welcome dont worry... I'm always with you |
 |
|
|
|
|
|
|
|