SQL Server : dynamic pivot over 5 columns(SQL Server:5 列的动态数据透视)
问题描述
我很难弄清楚如何在具有多列的 SQL Server 2008 中进行动态数据透视.
I'm having a very tough time trying to figure out how to do a dynamic pivot in SQL Server 2008 with multiple columns.
我的示例表如下:
我正在尝试按如下方式调整它:
and I'm trying the pivot it as follows:
我的SQL Server 2008查询如下创建表:
My SQL Server 2008 query is as follows to create the table:
T_Year
列将来可能会改变,但 T_TYPE
列一般都知道,所以我不确定我是否可以使用 PIVOT 函数的组合带有动态代码的 SQL Server?
The T_Year
column may change in the future but the T_TYPE
column is generally know, so I'm not sure if I can use a combination of the PIVOT function in SQL Server with dynamic code?
我尝试按照此处的示例进行操作:
I tried following the example here:
http://social.technet.microsoft.com/wiki/contents/articles/17510.t-sql-dynamic-pivot-on-multiple-columns.aspx
但我最终得到了奇怪的结果.
but I ended up with with weird results.
推荐答案
为了得到结果,您需要查看 Total
和 Volume 列.我的建议是首先编写查询的硬编码版本,然后将其转换为动态 SQL.
In order to get the result, you will need to look at unpivoting the data in the Total
and Volume
columns first before applying the PIVOT function to get the final result. My suggestion would be to first write a hard-coded version of the query then convert it to dynamic SQL.
UNPIVOT 过程将这些多列转换为行.UNPIVOT有几种方法,可以使用UNPIVOT功能,也可以使用CROSS APPLY.取消数据透视的代码类似于:
The UNPIVOT process converts these multiple columns into rows. There are a few ways to UNPIVOT, you can use the UNPIVOT function or you can use CROSS APPLY. The code to unpivot the data will be similar to:
这为您提供以下格式的数据:
This gives you data in the format:
然后就可以应用PIVOT函数了:
Then you can apply the PIVOT function:
既然你有正确的逻辑,你可以把它转换成动态 SQL:
Now that you have the correct logic, you can convert this to dynamic SQL:
这会给你一个结果:
这篇关于SQL Server:5 列的动态数据透视的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!