SQL 订阅 Queries/Self 加入

SQL Sub Queries/Self Join

这是一个自动呼叫反馈数据库,存储客户对每个问题的反馈。

我正在使用 SQL Server 2012 我在 table 名称中有以下数据 [NPS_Feedback]:

CLI         CallerID    Customer_Account    Question    Feedback        Date
34622968    F22141B854  400004775250        Q1          Satisfie        2016-03-25
34622968    F22141B854  400004775250        Q2          Not Satisfied   2016-03-25
34622968    F22141B854  400004775250        Q3          Not Satisfied   2016-03-25
30227453    GED903EDL   400001913180        Q1          Not Satisfied   2016-03-25
30227453    GED903EDL   400001913180        Q2          Satisfied       2016-03-25
30227453    GED903EDL   400001913180        Q3          Not Satisfied   2016-03-25
34622968    DAED19FDE   400004775250        Q1          Satisfied       2016-03-25
34622968    DAED19FDE   400004775250        Q2          Satisfied       2016-03-25
34622968    DAED19FDE   400004775250        Q3          Satisfied       2016-03-25

请帮助我使用 SQL 存储过程为 Reports 输出以下期望输出:

CLI     CallerID        Customer_Account    Q1             Q2             Q3              Date
34622968    F22141B854  400004775250        Satisfied      Not-Satisfied  Not-Satisfied   2016-03-25
30227453    GED903EDL   400001913180        Not-Satisfied  Satisfied      Not-Satisfied   2016-03-25
34622968    DAED19FDE   400004775250        Satisfied      Satisfied      Satisfied       2016-03-25

请注意:

Caller ID is Unique here for every call.

一个简单的 PIVOT 查询就可以了。

select CLI,CallerID,Customer_Account, [Q1],[Q2],[Q3], Date
from
(
    select 
    CLI,CallerID,Customer_Account,Question,Feedback,Date
    from [NPS_Feedback]
)s
pivot
(
    max(Feedback) for Question in ([Q1],[Q2],[Q3])
) p

除了使用PIVOT命令外,您还可以使用条件聚合:

SELECT
    CLI, 
    CallerID, 
    Customer_Account, 
    Q1 = MAX(CASE WHEN Question = 'Q1' THEN Feedback END),
    Q2 = MAX(CASE WHEN Question = 'Q2' THEN Feedback END),
    Q3 = MAX(CASE WHEN Question = 'Q3' THEN Feedback END),
    Date
FROM NPS_Feedback 
GROUP BY
    CLI, CallerID, Customer_Account, Date

ONLINE DEMO