我在列级别有一个包含年份和月份明智值的表格。
Table Structure
----------------
Franchise Year Month1 Month2 Month3 Month4 ....Month12
需要从当前月份通过SQL获取过去六个月值的值。有人可以帮忙吗?
EG。如果我需要过去六个月,它应该是当前年度记录,包含month2和month1值以及2013年记录,包括Month12,Month11,Month10,Month9值。
答案 0 :(得分:1)
DECLARE @MonthStart date
DECLARE @yyyy char(4)
DECLARE @mmm char(3)
DECLARE @monthColumn varchar(7)
DECLARE @SQL nvarchar(max)
set @MonthStart = DATEADD(day,1-DAY(getdate()), getdate())
set @MonthStart = DATEADD(month,-6,@MonthStart )
SET @SQL = 'SELECT Franchise'
WHILE DATEDIFF(month,@MonthStart,GETDATE() )>0
BEGIN
SET @yyyy = DATENAME(yyyy,@MonthStart )
SET @mmm = DATENAME(mm,@MonthStart )
SET @monthColumn = 'Month'+convert(varchar(2),DATEpart(m,@MonthStart ))
SET @SQL = @SQL +',
SUM(CASE WHEN Year = '+@yyyy+' THEN ['+@monthColumn +'] ELSE NULL END) AS ['+@mmm+' '+@yyyy +']'
set @MonthStart = DATEADD(month,1,@MonthStart )
END
/*Substitute with the name of the table*/
SET @SQL = @SQL +'
FROM [TableName] '
/*For demonstration purposes show the SQL to be executes*/
PRINT @SQL
/*Try to Execute it */
EXEC (@SQL)
这将生成并执行
行的语句SELECT Franchise,
SUM(CASE WHEN Year = 2013 THEN [Month8] ELSE NULL END) AS [Aug 2013],
SUM(CASE WHEN Year = 2013 THEN [Month9] ELSE NULL END) AS [Sep 2013],
SUM(CASE WHEN Year = 2013 THEN [Month10] ELSE NULL END) AS [Oct 2013],
SUM(CASE WHEN Year = 2013 THEN [Month11] ELSE NULL END) AS [Nov 2013],
SUM(CASE WHEN Year = 2013 THEN [Month12] ELSE NULL END) AS [Dec 2013],
SUM(CASE WHEN Year = 2014 THEN [Month1] ELSE NULL END) AS [Jan 2014]
FROM [TableName]