declare @SQL nvarchar(max)
,@Columns1 nvarchar(max)
,@Columns2 nvarchar(max);
set @Columns1 = N'';
set @Columns2 = N'';
select @Columns1 += iif(@Columns1 = '',quotename(Columns1),N','+quotename(Columns1))
from (select Month+' Count of TonerQty' as Columns1
from MPSSell
where Month is not null
and Month != ''
and Country in(select *
from [dbo].[UF_CSVToArray]('Hong Kong,South Korea,New Zealand,Philippines,Australia,India')
)
group by Month
) as colPvt1;
select @Columns2 += iif(@Columns2 = '',quotename(Columns2),N','+quotename(Columns2))
from
(select Month+' Count of PL' as Columns2
from
MPSSell
where Month is not null
and Month != ''
and Country in(select *
from [dbo].[UF_CSVToArray]('Hong Kong,South Korea,New Zealand,Philippines,Australia,India')
)
group by Month
) as colPvt2;
set @SQL = N'
select result1.Country
,['+stuff(@Columns1,1,1,'')
+', ['+stuff(@Columns2,1,1,'')
+' from(SELECT *
FROM (Select Country
,Month + '' Count of TonerQty'' as Columns1
,TonerQty as opValue1
from MPSSell
where Country is not null
and Country != ''''
and Month is not null
and Month != ''''
and Country in(Select *
from [dbo].[UF_CSVToArray](''Hong Kong,South Korea,New Zealand,Philippines,Australia,India'')
)
group by Country
,Month
,TonerQty
) as resPvt1
PIVOT(Count(opValue1) FOR Columns1 IN( ['+stuff(@Columns1,1,1,'')+')) as p
) as result1
join (SELECT *
FROM (Select Country
,Month + '' Count of PL'' as Columns2
,PL as opValue2
from MPSSell
where Country is not null
and Country != ''''
and Month is not null
and Month != ''''
and Country in(Select *
from [dbo].[UF_CSVToArray](''Hong Kong,South Korea,New Zealand,Philippines,Australia,India'')
)
group by Country
,Month
,PL
) as resPvt2
PIVOT(Count(opValue2) FOR Columns2 IN ( ['+stuff(@Columns2,1,1,'')+')) as p
) as result2
on result1.Country=result2.Country';
exec sp_executesql
@SQL;
This is my SQL pivot query which is working fine, but it is taking too much time to execute. Please help me how to can I reduce execution time.
Estimated Execution plan in Google Drive