Reputation: 353
I have a SQL query that I need to convert into a PIVOT table. Right now the data appears as such...
But I really want it to appear with the ProcessDesc as COLUMN HEADINGS and the "intersection" being DateCompleted, such as....
How can I do this exactly? The query that creates the original query is as follows...
SELECT DISTINCT E.DisplayName, EPM.DateCompleted, PS.SortNumber, PS.ProcessDesc
FROM dbo.EPM
INNER JOIN dbo.PS
ON EPM.EPS = PS.ID
INNER JOIN dbo.E
ON EPM.ID = E.ID
WHERE DisplayName IS NOT NULL
ORDER BY E.DisplayName, PS.SortNumber
Upvotes: 0
Views: 38
Reputation: 31879
Try this one:
#TEMP
here will be the one generated by your query:
SELECT DISTINCT E.DisplayName, EPM.DateCompleted, PS.SortNumber, PS.ProcessDesc
FROM dbo.EPM
INNER JOIN dbo.PS
ON EPM.EPS = PS.ID
INNER JOIN dbo.E
ON EPM.ID = E.ID
WHERE DisplayName IS NOT NULL
ORDER BY E.DisplayName, PS.SortNumber
declare @sql1 as varchar(4000) = ''
declare @sql2 as varchar(4000) = ''
declare @sql3 as varchar(4000) = ''
set @sql1 =
'select
DisplayName
'
select @sql2 = @sql2 +
' ,max(case when ProcessDesc = ''' + ProcessDesc + ''' then DateCompleted end) as [' + ProcessDesc +']
'
from #TEMP
order by ProcessDesc, ProcessSort
set @sql3 =
'
from #TEMP
group by DisplayName
ORDER BY DisplayName
'
print @sql1 + @sql2 +@sql3
exec(@sql1 + @sql2 +@sql3)
Upvotes: 1
Reputation: 26784
SELECT E.DisplayName,
MAX(CASE WHEN PS.ProcessDesc='Set-Up Form 1' THEN EPM.DateCompleted END) as [Set-Up Form 1],
MAX(CASE WHEN PS.ProcessDesc='Set-Up Form 2' THEN EPM.DateCompleted END) as [Set-Up Form 2],
MAX(CASE WHEN PS.ProcessDesc='Set-Up Form 3' THEN EPM.DateCompleted END) as [Set-Up Form 3]
FROM dbo.EPM
INNER JOIN dbo.PS
ON EPM.EPS = PS.ID
INNER JOIN dbo.E
ON EPM.ID = E.ID
WHERE DisplayName IS NOT NULL
GROUP BY E.DisplayName
ORDER BY E.DisplayName, PS.SortNumber
Upvotes: 0