2014-02-24 80 views
0

我有一個表在列級別明智的年份和月份值。將列明智的值分割成行

Table Structure 
---------------- 
Franchise Year Month1 Month2 Month3 Month4 ....Month12 

需要從當前月份通過SQL提取最近六個月值的值。任何人都可以幫忙嗎?

例如,如果我需要最近六個月,它應該是今年的月份2和月份1的值,以及月份12,月份11,月份10,月份9的值。

+0

行執行語句看起來你有沒有最佳的表結構。我不知道你的所有申請,但我會考慮一張有四列的表格:特許經營權,年,月,價值。對於那個表結構,這樣的查詢將更簡單。 – demas

+0

您是否正在爲Microsoft SQL Server和IBM DB2尋找答案? – WarrenT

回答

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 = '[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]