在 SQL Server 中动态旋转多个列
问题:
在 SQL Server 中,我们如何对表中的多个列执行动态透视,其中列名称可以在未来?
解决方案:
要实现多列动态旋转,请按照以下步骤操作:
1.取消数据透视:
select id, col = cast(t_year as varchar(4))+'_'+t_type+'_'+col, value from ATM_TRANSACTIONS t cross apply ( select 'total', total union all select 'volume', volume ) c (col, value);
2。应用 PIVOT 函数:
select ID, [2008_A_total], [2008_A_volume], [2008_B_total], [2008_B_volume], [2008_C_total], [2008_C_volume], [2009_A_total], [2009_A_volume] from ( select id, col = cast(t_year as varchar(4))+'_'+t_type+'_'+col, value from ATM_TRANSACTIONS t cross apply ( select 'total', total union all select 'volume', volume ) c (col, value) ) d pivot ( max(value) for col in ([2008_A_total], [2008_A_volume], [2008_B_total], [2008_B_volume], [2008_C_total], [2008_C_volume], [2009_A_total], [2009_A_volume]) ) piv;
3。转换为动态 SQL:
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) select @cols = STUFF((SELECT ',' + QUOTENAME(cast(t_year as varchar(4))+'_'+t_type+'_'+col) from ATM_TRANSACTIONS t cross apply ( select 'total', 1 union all select 'volume', 2 ) c (col, so) group by col, so, T_TYPE, T_YEAR order by T_YEAR, T_TYPE, so FOR XML PATH(''), TYPE ).value('.', 'NVARCHAR(MAX)') ,1,1,'') set @query = 'SELECT id,' + @cols + ' from ( select id, col = cast(t_year as varchar(4))+''_''+t_type+''_''+col, value from ATM_TRANSACTIONS t cross apply ( select ''total'', total union all select ''volume'', volume ) c (col, value) ) x pivot ( max(value) for col in (' + @cols + ') ) p ' execute sp_executesql @query;
输出:
这将生成具有指定列的透视结果。结果可能会有所不同,具体取决于表中的数据。
以上是如何在 SQL Server 中对多个列执行动态透视?的详细内容。更多信息请关注PHP中文网其他相关文章!