I want to optimize my sql query which i have written earlier (please see below attached sql query). This query is straight forward and very simple but this needs to be modified as it is failing at performance test, and I know the query is slow. My team lead did mention to me to use ‘Pivoting’ in the query but i didn’t catch his point how to pivot. Please can some one help me in this regard.
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
Instead of selecting into a @ColumnOrderTable, you can ommit that step and use a subselect.
Simplified original statement
The subselect itself can be ommitted by converting this statement using the PIVOT function.
Using PIVOT