これを行う 1 つの方法を次に示します。
DECLARE @SourceTable TABLE
(
[Quarter] NVARCHAR(20),
[cal_year] BIGINT,
[blue] NVARCHAR(20),
[green] NVARCHAR(20),
[yellow] NVARCHAR(20),
[red] NVARCHAR(20)
)
INSERT INTO @SourceTable ([Quarter],[cal_year],[blue],[green],[yellow],[red])
VALUES ('DEC',2011,'+31%','25-30%','22-24%','-21%')
,('MAR',2012,'+61%','50-60%','43-49%','-42%')
;WITH CTE([Quarter],[Color],[Value]) AS
(
SELECT [Quarter],[Color],[Value]
FROM
(
SELECT [Quarter],[blue],[green],[yellow],[red]
FROM @SourceTable
) data
UNPIVOT
(
[Value] FOR [Color] IN ([blue],[green],[yellow],[red])
)AS unpvt
)
SELECT *
FROM
(
SELECT Color,[Quarter],Value
FROM CTE
)AS src
PIVOT
(
MAX(Value) FOR [Quarter] IN ([MAR],[DEC] )
) AS pvtTbl
しかし、比較するデータが他にもあるとします。
CREATE TABLE #SourceTable
(
[Quarter] NVARCHAR(20),
[cal_year] BIGINT,
[blue] NVARCHAR(20),
[green] NVARCHAR(20),
[yellow] NVARCHAR(20),
[red] NVARCHAR(20)
)
INSERT INTO #SourceTable ([Quarter],[cal_year],[blue],[green],[yellow],[red])
VALUES ('DEC',2011,'+31%','25-30%','22-24%','-21%')
,('JAN',2012,'+11%','10-20%','13-49%','-12%')
,('FEB',2012,'+31%','25-35%','12-14%','-11%')
,('MAR',2012,'+71%','10-45%','13-59%','-11%')
,('APR',2012,'+11%','15-15%','12-24%','-51%')
,('MAY',2012,'+11%','40-60%','13-39%','-43%')
DECLARE @DynamicSQLStatement NVARCHAR(MAX)
SET @DynamicSQLStatement=N';WITH CTE([Quarter],[Color],[Value]) AS
(
SELECT [Quarter],[Color],[Value]
FROM
(
SELECT [Quarter],[blue],[green],[yellow],[red]
FROM #SourceTable
) data
UNPIVOT
(
[Value] FOR [Color] IN ([blue],[green],[yellow],[red])
)AS unpvt
)
SELECT *
FROM
(
SELECT Color,[Quarter],Value
FROM CTE
)AS src
PIVOT
(
MAX(Value) FOR [Quarter] IN ('+(SELECT SUBSTRING((SELECT '],[' + [Quarter] FROM #SourceTable FOR XML PATH('')),3,200)+']')+')
) AS pvtTbl'
EXECUTE sp_executesql @DynamicSQLStatement
DROP TABLE #SourceTable
異なる年の同じ月で動作させたい場合は、最後の例を最適化する必要があることに注意してください。