Click here to Skip to main content
15,891,033 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have few hundred thousand records to pivot dynamically. I've tried the following query and it works fine for a selected emploee id.
and when i want to pivot all the records of the employees, it is executing a very long time. Is it the right way to do or any better way to do? I have stopped the execution after half-an-hour as i didn't get an result.

What I have tried:

<pre lang="SQL">declare @cols nvarchar(max)=N'',@sql nvarchar(max)=N'',@uniqcols nvarchar(max)=N'' 
select @cols=isnull(@cols+',','')+QUOTENAME(concat(format(FromDate,'Y'),' to ',format(ToDate,'Y'))) 
from  salaries 
where EmpId=15001 
print @cols  
set @sql= 'select Firstname '+@cols+' 
from 
(     
select e.Empid,e.Firstname,concat(format(s.FromDate,''Y''),'' to '',format(s.ToDate,''Y'')) as period,s.salary      
from employees e join salaries s      
on e.EmpId=s.Empid      
where e.EmpId=15001 
)as source 
pivot 
(     
sum(salary) for period in ('+stuff(@cols,1,1,'')+') 
)as derived' 
print @sql 
exec sp_executesql @sql


<pre lang="SQL">declare @cols nvarchar(max)=N'',@sql nvarchar(max)=N'',@uniqcols nvarchar(max)=N'' 
select @cols=isnull(@cols+',','')+QUOTENAME(concat(format(FromDate,'Y'),' to ',format(ToDate,'Y'))) 
from  salaries
print @cols  
set @sql= 'select Firstname '+@cols+' 
from 
(     
select e.Empid,e.Firstname,concat(format(s.FromDate,''Y''),'' to '',format(s.ToDate,''Y'')) as period,s.salary      
from employees e join salaries s      
on e.EmpId=s.Empid      
)as source 
pivot 
(     
sum(salary) for period in ('+stuff(@cols,1,1,'')+') 
)as derived' 
print @sql 
exec sp_executesql @sql



Is there any other way to boost this dynamic pivot query within less time.
Thanks in advance.
Posted
Updated 8-Mar-18 20:15pm

1 solution

Check my past answer: Monthly sum in pivot table[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900