我的数据库有12列数字数据 - 每个月一列。
列名是
Jan, Feb, Mar. Apr, May, Jun, Jul, Aug, Sep, Oct, Nov and Dec.
我知道如何编写代码来汇总前3个月(1月,2月和3月)并返回Total总值。
SELECT Jan+Feb+Mar AS Total FROM MyData
问题:如何编写通用查询以给出前N个月的总和?
我是否需要编写代码来生成SQL语句,还是有其他方法?
答案 0 :(得分:2)
我认为你需要动态SQL来自动生成前N个月的查询。但您也可以定义一个包含所有总和的视图,例如
CREATE VIEW sums AS (
SELECT Jan AS total1,
SELECT Jan + Feb AS total2,
SELECT Jan + Feb + Mar AS total3,
...
SELECT Jan + Feb + Mar + ... + Nov + Dec AS total12
FROM yourTable
)
然后,您可以查询视图并访问您想要的任何总和。
答案 1 :(得分:0)
您可以生成一个可以使用sp_executesql
command
DECLARE @query NVARCHAR(MAX);
SET @query = 'SELECT #selectColumns# FROM tableName'
--- write your logic to get how many columns you need based on value of `N`
--- make their summation as stringToReplace (i.e. = 'Jan + Feb + Mar ...')
--- and replace them with #selectColumns# in @query
EXECUTE(@query)
PS:如果您使用的是MSSQL Server以外的数据库,您应该能够找到一些方法来执行字符串作为SQL命令。
例如,对于MySQL,有prepare
PREPARE stmt1 FROM @query;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
对于Oracle,您将拥有EXEC SQL EXECUTE IMMEDIATE :query;
答案 2 :(得分:0)
如果您正在使用 SQL Server ,那么您可以使用APPLY
运算符生成月份序列。
SELECT
SUM(a.Total) Totals
FROM table t
CROSS APPLY (
VALUES (1, 'Jan', Jan), (2, 'Feb', Feb), (3, 'Mar', Mar),
....
(12, 'Dec', Dec)
)a(Seq, Months, Total)
WHERE a.Seq <= 3 -- pass Nos of Months to get the sum of Totals