将SQL Server表列转换为行
将表列转换为行是一种非常有用的数据处理技巧。本文介绍了几种在SQL Server中完成此任务的方法。
UNPIVOT函数
UNPIVOT函数明确地将列转换为行,从而实现灵活的数据重组。例如,要转换示例表模式中'Indicator1'到'Indicator150'列:
<code class="language-sql">select id, entityId, indicatorname, indicatorvalue from yourtable unpivot ( indicatorvalue for indicatorname in (Indicator1, Indicator2, Indicator3) ) unpiv;</code>
使用CROSS APPLY和UNION ALL
或者,可以使用CROSS APPLY和UNION ALL组合多个子查询:
<code class="language-sql">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);</code>
使用CROSS APPLY和VALUES子句
在支持的SQL Server版本中,可以使用CROSS APPLY和VALUES子句:
<code class="language-sql">select id, entityid, indicatorname, indicatorvalue from yourtable cross apply ( values ('Indicator1', Indicator1), ('Indicator2', Indicator2), ('Indicator3', Indicator3), ('Indicator4', Indicator4) ) c (indicatorname, indicatorvalue);</code>
针对大量列的动态SQL
对于需要解旋的大量列的表,请考虑使用动态SQL以编程方式生成查询:
<code class="language-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;</code>
以上是如何高效地将SQL Server表列转换为行?的详细内容。更多信息请关注PHP中文网其他相关文章!