2017-04-19 57 views
0

我有一個表與下面的架構組查詢列名MSSQL

QUERYSET

,但我需要導出信息到另一個表,但結果,我需要必須是這樣的

RESULT

其中machine值必須與列名 一切都必須是一個SQL Server的名稱

回答

4

使用cross apply()values()到逆轉置數據:

select v.Machine, v.Temperature, v.Humidity, t.Fecha 
    from t 
    cross apply (values ('DR673',DR673_T,DR673_H),('DR677',DR677_T,DR677_H) 
    ) as v(Machine, Temperature, Humidity) 

要根據列名動態生成的SQL:

declare @cols nvarchar(max), @sql nvarchar(max); 

set @cols = stuff((
    select distinct 
     ',(''' + left(C.name,charindex('_',c.name)-1) 
     + ''','+ quotename(C.name) 
     + ','+ quotename(left(C.name,charindex('_',c.name))+'H') 
     +')' 
    from sys.columns c 
    where c.object_id = object_id('dbo.t') 
    and c.name like '%_T' 
    for xml path (''), type).value('.','nvarchar(max)') 
    ,1,1,''); 

set @sql = ' 
select v.Machine, v.Temperature, v.Humidity, t.Fecha 
from t 
    cross apply (values '[email protected]+' 
) as v(Machine, Temperature, Humidity)'; 

    select @sql as CodeGenerated; 
    --exec sp_executesql @sql; /* to execute the dynamic sql */ 

rextester演示:http://rextester.com/NAOT80053

回報:

+---------------------------------------------------------------------------------------+ 
|          CodeGenerated          | 
+---------------------------------------------------------------------------------------+ 
|  select v.Machine, v.Temperature, v.Humidity, t.Fecha        | 
|  from t                   | 
|  cross apply (values ('DR673',[DR673_T],[DR673_H]),('DR677',[DR677_T],[DR677_H]) | 
|  ) as v(Machine, Temperature, Humidity)           | 
+---------------------------------------------------------------------------------------+ 
+0

@GordonLinoff感謝您的錯字更正! – SqlZim

+0

非常感謝,解決我的問題:) –

+1

@CesarBecerra樂於幫助! – SqlZim