按列名MSSQL进行组查询

时间:2017-04-19 17:45:57

标签: sql sql-server database sql-server-2008

我有一个包含以下架构的表

QUERYSET

但我需要将该信息导出到另一个表,但我需要的结果必须是这样的

RESULT

其中,机器值必须来自其中一个列名称 一切都必须是Sql Server

1 个答案:

答案 0 :(得分: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 '+@cols+'
  ) 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)                                          |
+---------------------------------------------------------------------------------------+