【发布时间】:2011-09-22 04:00:10
【问题描述】:
我想优化我之前编写的 sql 查询(请参阅下面附加的 sql 查询)。这个查询很直接而且非常简单,但是需要修改它,因为它在性能测试中失败了,而且我知道查询很慢。我的团队负责人确实向我提到在查询中使用“Pivoting”,但我没有理解他的观点如何进行旋转。请有人在这方面帮助我。
Declare @tempTable Table(
DataSourceColumID int, fDataSourceID int, seqNum int, ColName varchar(50), HeaderName varchar(50)
)
Insert into @tempTable
(DataSourceColumID, fDataSourceID,seqNum, ColName,HeaderName)
Select 101,1,2,'col1', 'column 1'
Union ALL
Select 102,1,1,'col2', 'column 2'
Union All
Select 103,1,3,'col6', 'column 6'
Union All
Select 104,1,4,'col50', 'column 50'
select * From @tempTable
Declare @ColumnOrderTable table (col_A varchar(10),col_B varchar(10),col_C varchar(10),col_D varchar(10),col_E varchar(10),col_F varchar(10),col_G varchar(10))
Insert into @ColumnOrderTable (col_A ,col_B ,col_C ,col_D ,col_E ,col_F ,col_G )
select
Case When seqNum=1 then HeaderName else '' end as col_A,
Case When seqNum=2 then HeaderName else '' end as col_B ,
Case When seqNum=3 then HeaderName else '' end as col_C ,
Case When seqNum=4 then HeaderName else '' end as col_D ,
Case When seqNum=5 then HeaderName else '' end as col_E ,
Case When seqNum=6 then HeaderName else '' end as col_F,
Case When seqNum=7 then HeaderName else '' end as col_G
from @tempTable
select max(col_A) as col_A ,max(col_B) col_B,max(col_C) col_C,max(col_D) col_D,max(col_E) col_E,max(col_F) col_F,max(col_G) col_G From @ColumnOrderTable
【问题讨论】:
-
你读过这个吗?使用 PIVOT 和 UNPIVOT msdn.microsoft.com/en-us/library/ms177410.aspx
标签: sql sql-server sql-server-2005 tsql reportingservices-2005