Conditional running total across columns in SQL
I have this data:
Player StartBalance Day1Earned Day1Spent Day2Earned Day2Spent Day3Earned Day3Spent
Alex 10 0 0 3 -5 3 -15
How do I开发者_JAVA技巧 do a rolling total across column using SQL Server, so that the ending balance on Day 3 (actual data can expand to day 30) would be 0?
The daily balance is determined by the previous day balance + current day earned + current day spent, and if the sum of all 3 is less than 0 the balance would be 0.
I would make your total column computed (and persisted). You can then simply add up the columns and wrap them in a CASE and if less than zero set 0. I would use something like this (using ISNULL where needed).
(CASE WHEN ([DAY1]+[DAY2])<(0) THEN (0) ELSE [DAY1]+[DAY2] END)
精彩评论