[英]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 其中计算机值必须来自列名称之一的名称,而所有内容都必须针对Sql Server
using cross apply()
with values()
to unpivot your data: 使用
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)
To dynamically generate the sql based on column names: 要基于列名称动态生成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 demo: http://rextester.com/NAOT80053 extrester演示: 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) |
+---------------------------------------------------------------------------------------+
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.