简体   繁体   中英

Group Query by Column Name MSSQL

I have a table with the following schema

查询集

But i need to export that info to another table but the result that i need must be like this

结果

where machine value must be from the name of one of the column names everything must be for Sql Server

using cross apply() with values() to unpivot your data:

  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)

To dynamically generate the sql based on column names:

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 '+@cols+'
  ) as v(Machine, Temperature, Humidity)';

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

rextester demo: http://rextester.com/NAOT80053

returns:

+---------------------------------------------------------------------------------------+
|                                     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)                                          |
+---------------------------------------------------------------------------------------+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM