I'm working with an existing Table (cannot modify it) in SQL 2014
Simplified (example) table structure:
CREATE TABLE dbo.T1
(
sYear int NOT NULL,
m1 decimal(18, 2) NOT NULL,
m2 decimal(18, 2) NOT NULL,
m3 decimal(18, 2) NOT NULL,
m4 decimal(18, 2) NOT NULL,
m5 decimal(18, 2) NOT NULL,
m6 decimal(18, 2) NOT NULL,
m7 decimal(18, 2) NOT NULL,
m8 decimal(18, 2) NOT NULL,
m9 decimal(18, 2) NOT NULL,
m10 decimal(18, 2) NOT NULL,
m11 decimal(18, 2) NOT NULL,
m12 decimal(18, 2) NOT NULL
)
The table represents a "monthly budget" or what's remaining thereof, where m1 to m12 represent the months
So Sample Data for the row would look something like this:
Insert into dbo.T1
Values( 2017,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000,1000)
Now my task is this, if a user wants to spend an amount in a specific month, I need to remove the spend amount from that specific months remaining budget, providing it has sufficient funds. If not I need to remove form subsequent months until the full value of the spend has been removed.
I've tried using Case statements and summing columns, but it became ridiculously long....too many cases. So what I ended up doing is to create a temp table where each column from the original table becomes a row & then summing those row vlaues until I've reached the Spend Amount.. (used this answer as an example of how to achieve this:Select running total until specific SUM is reached)
Still not convinced that's the best way for my scenario, so does anyone know of a way to sum across columns of a specific row or of any other/ better way of achieving this?