我的输入是:
date Costed Celldata
8-Apr-13 1 15
15-Apr-13 1 24
22-Apr-13 1 36
我需要输出为:
date 8-Apr-13 15-Apr-13 22-Apr-13
Costed 1 1 1
Celldata 15 24 36
我申请的查询是:
CREATE TABLE testing1(Spot_dt date, Costed INT, celldata INT)
INSERT INTO testing1 (Spot_dt,Costed,celldata) values ('2012-04-08',1,15);
INSERT INTO testing1 (Spot_dt,Costed,celldata) values ('2012-04-15',1,24);
INSERT INTO testing1 (Spot_dt,Costed,celldata) values ('2012-04-22',1,36);
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(Spot_dt)
from testing1
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT Costed,' + @cols + '
from
(
select Spot_dt, Costed, CellData
from testing1
) x
pivot
(
min(CellData)
for Spot_dt in (' + @cols + ')
) p '
execute(@query)
我收到的输出是:
8-Apr-13 15-Apr-13 22-Apr-13
1 1 1
15 24 36
所以基本上我需要一个额外的列,在其中我可以将列标题作为行值。