SQL Server根据参数求和表字段



我有一个包含12个不同月份的值的表

Table
{
   January INT,
   February INT,
   etc.
}

和我需要求和从特定月份的值,这些数字我保存在表中(求和的月数可以从1到12不等):

    DECLARE @Months TABLE
    (
        Number INT
    )

所以我肯定需要一个大的案例和CTE,但我真的不知道如何做到这一点

case语句并没有那么糟糕:

select sum((case when m.month = 1 then Jan else 0 end) +
           (case when m.month = 2 then Feb else 0 end) +
           . . .
           (case when m.month = 12 then Dec else 0 end)
          )
from atable a cross join
     @Months m;

你可能也想要一个group by。上面的代码将只返回整个表的一行。

最新更新