Hi @Hellothere8028 ,
Please refer below dynamic way:
drop table if exists #temp
;with cte as (
select raisedby,year(raised) as y, left(DATENAME(month,raised),3) as m, raised,case when cast(raised as time)<cast(resolved as time) then
cast(REPLACE(LEFT(CAST(DATEADD(SECOND, cast(DATEDIFF(MINUTE,cast(raised as time),cast(resolved as time)) as float)/60 * 3600, 0) AS TIME),5),':','.') as float)
else cast(REPLACE(LEFT(CAST(DATEADD(SECOND, cast(DATEDIFF(MINUTE,cast(raised as time),dateadd(hour,24,cast(resolved as time))) as float)/60 * 3600, 0) AS TIME),5),':','.') as float)
end diff from ##input)
select raisedby,y,m,m+cast(y as char(4)) ym,
count(raised) as raised,
sum(case when diff is null then 1 else 0 end) tobe,
AVG(diff) avg
into #temp
from cte
group by raisedby,y, m
declare @sql nvarchar(max)=''
declare @s nvarchar(max)=''
SELECT @s=STUFF(( SELECT ' max(case when ym = ''' + ym +''' then raised end) as numberofescalationsraisedin'+ym
+',max(case when ym = ''' + ym +''' then avg end) as averagetimetaketoresolveescalationsraisedin'+ym+','
FROM (select distinct ym from #temp) a
FOR XML PATH('') ), 1, 1, '')
select @s=SUBSTRING(@s,1,len(@s)-1)
set @sql ='
select raisedby personraised,
max(tobe) as numberofescalationspendingtoberesolved,
'+@s+'
from #temp
group by raisedby
order by raisedby desc'
EXECUTE sp_executesql @sql
Best regards,
Melissa
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.