SQL 查询同一列上的多个数据透视表

SQL Query for multiple Pivot on same column

根据我的要求,我需要在同一列上应用 pivot 两次以获得与列 header 不同的值。 请在下面查看数据如何显示在 table 和预期结果中。

Table

Question Response TranslatedResponse activityid createdon
Reason Testing testaus 1 01-01-2022
EMail abc@gmail.com abc@gmail.com 1 01-01-2022
Action test testata 1 01-01-2022

期望的输出:

Email Reason Action Translated Action Translated Reason activityid createdon
abc@gmail.com Testing test testata testaus 1 01-01-2022

我通过使用下面的查询实现了这一点,它通过使用内部连接和两个不同的 pivot select 语句来实现。

SELECT A.activityid,
       A.createdon,
       A.[Email],
       A.[Action],
       A.[Reason],
       B.[Translated Action],
       B AS [Translated Reason]
FROM (SELECT *
      FROM (SELECT activityid, createdon, question, response FROM Table) subquery
      PIVOT (MAX(response)
             FOR question IN ([Email], [Reason], [Action])) pv1) A
     INNER JOIN (SELECT activityid,
                        createdon,
                        question,
                        translatedresponse,
                        [Action] AS [Translated Action],
                        [Reason] AS [Translated Reason]
                 FROM (SELECT activityid,
                              createdon,
                              question,
                              response,
                              translatedresponse
                       FROM Table) subquery
                 PIVOT (MAX(translatedresponse)
                        FOR question IN ([Email], [Action], [Reason])) pv2) B ON A.activityid = B.activityid;

是否有另一种编写 SQL 查询的方式来优化和摆脱内连接。

使用条件聚合:

SELECT MAX(CASE Question WHEN 'Email' THEN Response END) AS Email,
       MAX(CASE Question WHEN 'Reason' THEN Response END) AS Reason,
       MAX(CASE Question WHEN 'Action' THEN Response END) AS Action,
       MAX(CASE Question WHEN 'Reason' THEN TranslatedResponse END) AS TranslatedReason,
       MAX(CASE Question WHEN 'Action' THEN TranslatedResponse END) AS TranslatedAction,
       activityid,
       createdon
FROM dbo.YourTable
GROUP BY activityid,
         createdon;