我正在努力使用SQL从表中转换下面的数据:
company name 01/05/15 24/04/15 17/04/15 10/04/150 3/04/15
companyA Stage 2 Stage 1
companyB Stage 2 Stage 1
companyC Stage 3 Stage 2 Stage 1
采用以下格式:
company name Stage 1 Stage 2 Stage 3
companyA 10/04/15 01/05/15
companyB 17/04/15 01/05/15
companyC 03/04/15 24/04/15 01/05/15
我尝试了Pivot
,但似乎无效。
答案 0 :(得分:0)
首先UNPIVOT
然后PIVOT
:
DECLARE @t TABLE
(
c VARCHAR(20) ,
[01/05/15] VARCHAR(20) ,
[24/04/15] VARCHAR(20) ,
[17/04/15] VARCHAR(20) ,
[10/04/150] VARCHAR(20) ,
[3/04/15] VARCHAR(20)
)
INSERT INTO @t
VALUES ( 'Company A', 'Stage 2', 'Stage 1', NULL, NULL, NULL ),
( 'Company B', 'Stage 2', 'Stage 1', NULL, NULL, NULL ),
( 'Company C', 'Stage 3', 'Stage 2', 'Stage 1', NULL, NULL )
SELECT * FROM @t
UNPIVOT (a FOR b IN([01/05/15], [24/04/15], [17/04/15], [10/04/150], [3/04/15])) u
PIVOT (MAX(b) FOR a in([Stage 1],[Stage 2],[Stage 3])) p
输出:
c Stage 1 Stage 2 Stage 3
Company A 24/04/15 01/05/15 NULL
Company B 24/04/15 01/05/15 NULL
Company C 17/04/15 24/04/15 01/05/15