需要PIVOT表的帮助

时间:2014-11-20 23:13:22

标签: sql sql-server

我有一个SQL查询,我需要转换为PIVOT表。现在数据显示为......

enter image description here

但我真的希望它与ProcessDesc一起显示为COLUMN HEADINGS和"交叉点"正在进行DateCompleted,例如....

enter image description here

我该怎么做呢?创建原始查询的查询如下...

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

2 个答案:

答案 0 :(得分:1)

试试这个:

#TEMP此处将是您的查询生成的内容:

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

使用DYNAMIC SQL的解决方案

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)

答案 1 :(得分:0)

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