我有下表。每行存儲一系列指定列中的值。在SQL Server 2005中查找根據當前月份的列總數
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)
.
.
.
我想要做的是,根據年份的月份,對於每一行,總結了從第一列(月)截至及包括表示當前月列中的值(八月例如)。我懷疑這可能會涉及某些以月份爲參數的函數。當然會有成千上萬的行,而不是每行都是唯一的。
我不太清楚從哪裏開始,或者使用哪個sql內置函數/關鍵字來使用它。任何人都可以將我指向正確的方向嗎?
UPDATE:
基於舍甫琴科M的解決方案,我想出了這個。
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
矩陣表具有是單位矩陣與左下半填充有1的而不是0的(列名開始與arbitry前綴,在這種情況下「P」,以及後跟一個數字)。在結尾添加一個額外的列以標識每一行。只要矩陣表足夠大,矩陣表對於其他問題以及將來也會有用。
這張表的PK是什麼?你也打開改變架構? –
是的,我願意改變模式。我可以包含一個自動遞增的PK。這不是一個問題。 – deutschZuid