Reputation: 7712
I have data that looks as follows:
I would like to convert this into a single row with the following columns:
SubId,
Zone1ReadTime,
Zone1ChamberPressure
Zone1ChamberTemperature,
Zone2ReadTime,
Zone2ChamberPressure
Zone2ChamberTemperature,
etc...
Essentially, for each of the 20 zones for a particular SubId, I want to create a set of 20 columns. I've used the PIVOT function a few times, but don't really know how to handle this.
Upvotes: 0
Views: 69
Reputation: 2080
Query
create table #demo (SubId int,zone int,ReadTime datetime,ChamberPressure float,ChamberTemp float)
insert into #demo (SubId ,zone ,ReadTime ,ChamberPressure ,ChamberTemp )
values
(1,1,GETDATE(),0.133156,98.4),
(1,2,GETDATE()+1,0.13435,76.4),
(1,3,GETDATE()+2,0.62346,3.4),
(1,4,GETDATE()+3,0.63426,34.4),
(1,5,GETDATE()+4,0.76457,43.4)
select * from
(select SubId
--,zone
,case
when COL='ReadTime' then 'Zone'+ CAST(zone as varchar) + 'ReadTime'
when COL='ChamberPressure' then 'Zone'+ CAST(zone as varchar) + 'ChamberPressure'
when COL='ChamberTemp' then 'Zone'+ CAST(zone as varchar) + 'ChamberTemp'
end New_Col,
Value
from (select SubId
,zone
,CAST(ReadTime as varchar) ReadTime
,CAST(ChamberPressure as varchar) ChamberPressure
,CAST(ChamberTemp as varchar) ChamberTemp
from #demo
)a
UNPIVOT
(
Value
for COL in ([ReadTime],[ChamberPressure],[ChamberTemp])
)UPVT
)b
pivot
(
MAX(Value)
for New_Col in (Zone1ReadTime,Zone1ChamberPressure,Zone1ChamberTemp
,Zone2ReadTime,Zone2ChamberPressure,Zone2ChamberTemp
,Zone3ReadTime,Zone3ChamberPressure,Zone3ChamberTemp
,Zone4ReadTime,Zone4ChamberPressure,Zone4ChamberTemp
,Zone5ReadTime,Zone5ChamberPressure,Zone5ChamberTemp)
) PVT
drop table #demo
| SUBID | ZONE1READTIME | ZONE1CHAMBERPRESSURE | ZONE1CHAMBERTEMP | ZONE2READTIME | ZONE2CHAMBERPRESSURE | ZONE2CHAMBERTEMP | ZONE3READTIME | ZONE3CHAMBERPRESSURE | ZONE3CHAMBERTEMP | ZONE4READTIME | ZONE4CHAMBERPRESSURE | ZONE4CHAMBERTEMP | ZONE5READTIME | ZONE5CHAMBERPRESSURE | ZONE5CHAMBERTEMP |
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
| 1 | Aug 1 2013 5:50AM | 0.133156 | 98.4 | Aug 2 2013 5:50AM | 0.13435 | 76.4 | Aug 3 2013 5:50AM | 0.62346 | 3.4 | Aug 4 2013 5:50AM | 0.63426 | 34.4 | Aug 5 2013 5:50AM | 0.76457 | 43.4 |
You may have to cast
the result to required datetype
.
Upvotes: 1