SQL小提琴
询问
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 |
您可能必须cast
将结果设置为 required datetype
。