gpt4 book ai didi

sql-server - 根据 SQL Server 2005 中的当前月份查找列的总和

转载 作者:行者123 更新时间:2023-12-02 07:45:59 25 4
gpt4 key购买 nike

我有下表。每行存储一系列跨指示列的值。

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 内置函数/关键字。谁能给我指出正确的方向?

更新:

基于 Andriy 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 填充(列名以任意前缀开头,在本例中为“p”,后跟一个数字)。在末尾添加一个额外的列来标识每一行。只要足够大,矩阵表在未来对其他问题也很有用。

最佳答案

如果我的其他答案中建议的更改过于激进而无法采用,那么这是@Filip De Vos 解决方案的替代方案:

SELECT
SUM(
CASE v.number
WHEN 1 THEN Jan
WHEN 2 THEN Feb
WHEN 3 THEN Mar
WHEN 4 THEN Apr
WHEN 5 THEN May
WHEN 6 THEN Jun
WHEN 7 THEN Jul
WHEN 8 THEN Aug
WHEN 9 THEN Sep
WHEN 10 THEN Oct
WHEN 11 THEN Nov
WHEN 12 THEN Dec
END
) AS Total
FROM MonthlyData m
CROSS JOIN master..spt_values v
WHERE v.type = 'P'
AND v.number BETWEEN 1 AND MONTH(GETDATE())

master..spt_values table 是用于内部目的的系统表,但也可用于用户查询。它的一个子集包含一个从 0 到 2047 的整数列表,在许多情况下可以用作现成的 tally table .

关于sql-server - 根据 SQL Server 2005 中的当前月份查找列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7018516/

25 4 0
文章推荐: php - 我如何在我的网站上进行直播
文章推荐: PHP 开关大小写 Url
文章推荐: ruby-on-rails - rails 3 : How do I create options in a