用CTE和箱子冷凝行

时间:2018-04-24 02:31:11

标签: sql-server tsql

我在尝试正确分组/压缩此查询的结果时遇到了问题。

这就是我想要的结果:

Person ID | Plan ID 1 | Plan ID 2 | Plan ID 3
   1         A            B           C
   2         A            B           NULL

但我得到的是:

Person ID | Plan ID 1 | Plan ID 2 | Plan ID 3
    1        A            NULL        NULL
    1        NULL         B           NULL
    1        NULL         NULL        C
    2        A            NULL        NULL
    2        NULL         B           NULL
    2        NULL         NULL        NULL

我想过可能尝试使用两台CTE,但无法正常使用它。

这是SQL:

;WITH CTE AS 
(
    SELECT 
        p.id [Person ID], plan.id [Plan ID],
        ROW_NUMBER() OVER (PARTITION BY a.p_id ORDER BY plan.year DESC) [PlanRow],
        ROW_NUMBER() OVER (PARTITION BY a.p_id ORDER BY a.close_date DESC) [AcctRow],
        a.close_date [Most Recent Close Date]
    FROM
        person p
    JOIN
        Account a ON p.id = a.p_id
    JOIN
        plan plan ON a.plan_id = plan.id
)
SELECT
    cte.[Person ID],
    CASE 
       WHEN cte.PlanRow = 1 THEN cte.[Plan ID] 
    END [Plan ID 1],
    CASE 
       WHEN cte.PlanRow = 2 THEN cte.[Plan ID] 
    END [Plan ID 2],
    CASE 
       WHEN cte.PlanRow = 3 THEN cte.[Plan ID] 
    END [Plan ID 3],
    CASE 
       WHEN cte.[AcctRow] = 1 THEN cte.[Most Recent Term Date] 
    END [Term Date]
FROM
    cte

我已经尝试在select语句中删除不必要的列并重命名了一些内容,但这个想法就在那里。

有什么建议吗?

1 个答案:

答案 0 :(得分:1)

您需要聚合:

select cte.[Person ID],
       max(case when cte.PlanRow = 1 then cte.[Plan ID] end) as [Plan ID 1],
       max(case when cte.PlanRow = 2 then cte.[Plan ID] end) as [Plan ID 2],
       max(case when cte.PlanRow = 3 then cte.[Plan ID] end) as [Plan ID 3],
       max(case when cte.[FlexRow]=1 then cte.[Most Recent Term Date] end) as [Term Date]
from cte
group by cte.[Person ID];