提高Dynamic Pivot

时间:2018-03-07 06:42:21

标签: sql sql-server pivot

我有几十万条记录动态转动。 我已经尝试了以下查询,它适用于选定的员工。

    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

查询计划:[https://drive.google.com/file/d/1O7G4sETr4XteKbV2lYo7Ph2DaMty6943/view?usp=sharing]

当我想转动员工的所有记录时,它正在执行很长时间。这是正确的做法还是更好的方式? 如何在短时间内检索枢轴?

    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

0 个答案:

没有答案