这是执行此操作的一种方法:
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
请注意,如果您希望它与不同年份的相同月份一起工作,则应该优化最后一个示例。