查询未产生所需结果

时间:2016-04-25 22:14:59

标签: sql sql-server sql-server-2008

下面是我的表格的表格结构 - group_table

enter image description here

我需要的结果应该如下

以下是我尝试使用的查询。但不能按要求产生结果。

SELECT * FROM 
(
SELECT A.PARENTID,A.NAME,A.CAPTION,A.PMKID,A.MKTPLANID,A.CATEGORY
FROM GROUP_TABLE A
)P
PIVOT
(
MAX(NAME)
FOR CAPTION IN ([Rollup],[Appeal Category],[PME])
)S

1 个答案:

答案 0 :(得分:2)

使用条件聚合可能会更容易:

select mktplanid,
       max(case when caption = 'Rollup' then name end) as rollup,
       max(case when caption = 'Appeal Category' then name end) as appealcategory,
       max(case when caption = 'Planned Appeal' then name end) as plannedappeal,
       max(case when caption = 'PME' then name end) as PME,
       max(pmkid) as pmkid
from (select gt.*,
             row_number() over (partition by caption, mktplanid ORDER BY mktplanid) as seqnum 
      from group_table gt
     ) gt
group by mktplanid, seqnum;