I have the following table. Each row stores a series of values across the columns indicated.
create table MonthlyData (
Jan int not null,
Feb int not null,
Mar int not null,
Apr int not null,
May int not null,
Jun int not null,
Jul int not null,
Aug int not null,
Sep int not null,
Oct int not null,
Nov int not null,
Dec int not null
)
insert into table (3, 1, 3, 4, 5, 6, 7, 8, 9, 4, 3, 2)
.
.
.
What I want to do is, depending on the month of the year, for each row, sum up the values from the first column (Jan) up to and including the column that represents the current month (Aug for example). I suspect that this will probably involve some sort of function that takes the month as the parameter. There will, of course be thousands of rows and not every row will be unique.
I am not quite sure where to start on this or which sql built-in functions/keywords to use for this. Would anyone be able to point me to the right direction?
UPDATE:
Based on Andriy M's solution, I came up with this.
declare @currentMonth int
set @currentMonth = 8
select sum(p1*Jan+p2*Feb+p3*Mar+p4*Apr+
p5*May+p6*Jun+p7*Jul+p8*Aug+
p9*Sep+p10*Oct+p11*Nov+p12*Dec) as 'Balance'
from MonthlyData md
cross join MatrixTable mt
where mt.period = @currentMonth
The matrix table has is an identity matrix with the lower left half filled with 1's instead of 0's (column names start with an arbitry prefix, in this case 'p', and followed by a number). An extra column is added at the end to identify each row. The matrix table will be useful for other problems as well in the future, as long as it is sufficiently big.