寻找优雅的(或任何)解决方案以将列转换为行。
这是一个示例:我有一个具有以下架构的表:
[ID] [EntityID] [Indicator1] [Indicator2] [Indicator3] ... [Indicator150]
这是我想要得到的结果:
[ID] [EntityId] [IndicatorName] [IndicatorValue]
结果值为:
1 1 'Indicator1' 'Value of Indicator 1 for entity 1' 2 1 'Indicator2' 'Value of Indicator 2 for entity 1' 3 1 'Indicator3' 'Value of Indicator 3 for entity 1' 4 2 'Indicator1' 'Value of Indicator 1 for entity 2'
等等..
这有意义吗?您对在哪里看以及如何在T-SQL中完成操作有任何建议吗?
您可以使用UNPIVOT函数将列转换为行:
select id, entityId, indicatorname, indicatorvalue from yourtable unpivot ( indicatorvalue for indicatorname in (Indicator1, Indicator2, Indicator3) ) unpiv;
请注意,要取消透视的列的数据类型必须相同,因此您可能必须在应用取消透视之前转换数据类型。
您还可以CROSS APPLY与UNION ALL一起使用来转换列:
CROSS APPLY
select id, entityid, indicatorname, indicatorvalue from yourtable cross apply ( select 'Indicator1', Indicator1 union all select 'Indicator2', Indicator2 union all select 'Indicator3', Indicator3 union all select 'Indicator4', Indicator4 ) c (indicatorname, indicatorvalue);
根据您的SQL Server版本,您甚至可以将CROSS APPLY与VALUES子句一起使用:
select id, entityid, indicatorname, indicatorvalue from yourtable cross apply ( values ('Indicator1', Indicator1), ('Indicator2', Indicator2), ('Indicator3', Indicator3), ('Indicator4', Indicator4) ) c (indicatorname, indicatorvalue);
最后,如果您有150列要取消透视,并且您不想对整个查询进行硬编码,则可以使用动态SQL生成sql语句:
DECLARE @colsUnpivot AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @colsUnpivot = stuff((select ','+quotename(C.column_name) from information_schema.columns as C where C.table_name = 'yourtable' and C.column_name like 'Indicator%' for xml path('')), 1, 1, '') set @query = 'select id, entityId, indicatorname, indicatorvalue from yourtable unpivot ( indicatorvalue for indicatorname in ('+ @colsunpivot +') ) u' exec sp_executesql @query;