Translate
Saturday, 6 July 2013
Transposing Rows to columns without aggregation and Displaying column header as First column In sql server 2008(pivot)
swap the N rows to columns without aggregation function in sql server 2008
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);
select * from testing1
Spot_dt Costed celldata
2012-04-08 1 15
2012-04-15 1 24
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 valtype dates, ' + @cols + '
from (select Spot_dt, Costed, CellData from testing1) as x
unpivot (vals for valtype in (Costed, celldata)) as u
pivot (min(vals) for spot_dt in (' + @cols + ')) as p'
execute(@query)
dates 2012-04-08 2012-04-15 2012-04-22
CellData 15 24 36
Costed 1 1 1
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment