MS SQL调查表行转列问题:PIVOT出NULL/CASE仅一行求助
MS SQL 调查数据行转列解决方案
问题分析
现有调查数据表结构如下:
| Question | answer | group | enterprise |
|---|---|---|---|
| 1 | softcame | 2022-09-01 | softcame |
| 2 | edgar | 2022-09-01 | softcame |
| 5 | 1 | 2022-09-01 | softcame |
| 6 | 1 | 2022-09-01 | softcame |
| 3 | Si | 2022-09-01 | softcame |
| 4 | SI | 2022-09-01 | softcame |
| 1 | softcame america | 2022-09-01 | softcame america |
| 2 | edgar 2 | 2022-09-01 | softcame america |
| 5 | 2 | 2022-09-01 | softcame america |
| 6 | 2 | 2022-09-01 | softcame america |
| 3 | No | 2022-09-01 | softcame america |
| 4 | No | 2022-09-01 | softcame america |
| 1 | softcame norte | 2022-09-01 | softcame norte |
| 2 | edgar 3 | 2022-09-01 | softcame norte |
| 5 | 3 | 2022-09-01 | softcame norte |
| 6 | 3 | 2022-09-01 | softcame norte |
| 3 | Si | 2022-09-01 | softcame norte |
| 4 | No | 2022-09-01 | softcame norte |
需求是将Question字段转为列,answer作为对应列的值,最终按enterprise分组输出结果。
原代码错误点
PIVOT语句错误:
- 引用不存在的字段
no_pregunta,实际应为Question - 查询条件中日期格式
'01/09/2022'与表中存储的2022-09-01格式不匹配,导致过滤错误 - 未指定按
enterprise分组,多余的GROUP BY子句破坏了分组逻辑
- 引用不存在的字段
CASE+GROUP BY语句错误:
- 子查询中字段拼写错误(
grpup应为group) GROUP BY仅包含group,未加入enterprise,导致同一分组下的所有企业结果被合并为一行
- 子查询中字段拼写错误(
正确解决方案
方案一:使用PIVOT实现行转列
修正字段名、日期格式,并按enterprise保留分组:
SELECT enterprise, [1], [2], [3], [4], [5], [6] FROM ( SELECT enterprise, Question, answer FROM Respuestas_Encuestas_Todas WHERE survey = 'SurveName' AND [group] = '2022-09-01' -- group是SQL关键字,需加方括号包裹,日期格式与表中保持一致 ) AS SourceData PIVOT ( MAX(answer) -- 用MAX聚合确保每个Question对应唯一answer FOR Question IN ([1], [2], [3], [4], [5], [6]) ) AS PivotTable;
方案二:使用CASE+GROUP BY实现行转列
修正拼写错误,将enterprise加入GROUP BY子句:
SELECT enterprise, MAX(CASE WHEN Question = 1 THEN answer END) AS [1], MAX(CASE WHEN Question = 2 THEN answer END) AS [2], MAX(CASE WHEN Question = 3 THEN answer END) AS [3], MAX(CASE WHEN Question = 4 THEN answer END) AS [4], MAX(CASE WHEN Question = 5 THEN answer END) AS [5], MAX(CASE WHEN Question = 6 THEN answer END) AS [6] FROM Respuestas_Encuestas_Todas WHERE survey = 'survey name' AND [group] = '2022-09-01' GROUP BY enterprise, [group]; -- 同时按enterprise和group分组,确保结果准确
说明
- 两个方案都会输出3行结果,对应3个enterprise的调查数据
group是SQL关键字,查询时必须用方括号[group]包裹避免语法错误- 日期格式需与表中存储的
YYYY-MM-DD保持一致,否则会过滤不到目标数据
内容的提问来源于stack exchange,提问作者Edgar
相关产品推荐
相关产品推荐

