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 = '[email protected]+' THEN ['[email protected] +'] ELSE NULL END) AS ['[email protected]+' '[email protected] +']'
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]
行執行語句看起來你有沒有最佳的表結構。我不知道你的所有申請,但我會考慮一張有四列的表格:特許經營權,年,月,價值。對於那個表結構,這樣的查詢將更簡單。 – demas
您是否正在爲Microsoft SQL Server和IBM DB2尋找答案? – WarrenT