SQL Server Pivot table 用于调查回复

SQL Server Pivot table for survey responses

我有一个 sql 服务器 table 使用以下数据调用调查

+------------+--------------+----+----+----+----+
| ModuleCode | SurveyNumber | Q1 | Q2 | Q3 | Q4 |
+------------+--------------+----+----+----+----+
| NME3519    |            1 |  5 |  4 |  5 |  3 |
| NME3519    |            2 |  3 |  3 |  2 |  1 |
| NME3519    |            3 |  4 |  3 |  2 |  1 |
| NME3520    |            1 |  4 |  3 |  2 |  1 |
| NME3519    |            4 |  4 |  2 |  2 |  1 |
+------------+--------------+----+----+----+----+

我希望能够一次报告一个模块,结果如下:

            Count of scores
+----------+---+---+---+---+---+
| Question | 1 | 2 | 3 | 4 | 5 |
+----------+---+---+---+---+---+
| Q1       | 0 | 0 | 1 | 2 | 1 |
| Q2       | 0 | 1 | 2 | 1 | 0 |
| Q3       | 0 | 3 | 0 | 0 | 1 |
| Q4       | 3 | 0 | 1 | 0 | 0 |
+----------+---+---+---+---+---+

根据其他示例,我非常确定我需要先逆向旋转然后再旋转,但我无法使用自己的数据获得任何结果。

非常感谢

理查德

逆透视和聚合:

select v.question,
       sum(case when v.score = 1 then 1 else 0 end) as score_1,
       sum(case when v.score = 2 then 1 else 0 end) as score_2,
       sum(case when v.score = 3 then 1 else 0 end) as score_3,
       sum(case when v.score = 4 then 1 else 0 end) as score_4,
       sum(case when v.score = 5 then 1 else 0 end) as score_5
from responses r cross apply
     ( values ('Q1', r.q1), ('Q2', r.q2), ('Q3', r.q3), ('Q4', r.q4), ('Q5', r.q5)
     ) v(question, score)
group by v.question;

此版本使用横向连接进行反透视。我发现语法更简单,横向连接更强大。为什么要学习 unpivot 其他东西做同样的事情更简洁、更强大并且具有相同的性能?

至于旋转,它使用条件聚合。根据我使用 SQL 服务器的经验,这与 pivot.

的性能几乎相同