用于调查响应的SQL Server Pivot表

时间:2018-03-12 19:17:59

标签: sql sql-server pivot unpivot

我有一个名为survey的sql server表,其中包含以下数据

+------------+--------------+----+----+----+----+
| 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 |
+----------+---+---+---+---+---+

我非常确定从其他示例中我需要移植然后转动,但我无法使用自己的数据。

非常感谢

理查德

1 个答案:

答案 0 :(得分:1)

Unpivot and aggregate:

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 Server的经验,这与pivot具有几乎相同的性能。