在SQL查询中,如何将一组结果折叠成一行,其中每个结果都是特定CASE
的乘积?当然,我的示例将有助于说明我要提出的问题...
我正在针对Postgres表运行查询,该表返回多组调查答案-该调查简短,只有4个问题,每个问题都有一个唯一的question_id
-由于可以提交多个调查,因此{ {1}}字段本身并不强制唯一性,并且将具有重复值,其中每组重复值代表一个完整的调查响应。例如,这里是question_id
:
survey_answers
理想情况下,我希望能够进一步将此结果查询/处理为输出,其中每组结果都折叠为一行:
question_id | answer
----------------------------
a | 10
b | foo
c | 9
d | bar
a | 2
b | baz
c | 4
d | zip
但是,我不太擅长SQL,因此无法完全正常工作。我能得到的最接近的是使用此查询:
score_1 | reason_1 | score_2 | reason_2
----------------------------------------------
10 | foo | 9 | bar
2 | baz | 4 | zip
但这会生成一个表格,其中每个结果都在自己的行上(我对这个结果并不感到惊讶-只是不确定如何将其放入我要寻找的内容中):
SELECT
CASE WHEN survey_answers.question_id = 'a' THEN survey_answers.answer END AS score_1,
CASE WHEN survey_answers.question_id = 'b' THEN survey_answers.answer END AS reason_1,
CASE WHEN survey_answers.question_id = 'c' THEN survey_answers.answer END AS score_2,
CASE WHEN survey_answers.question_id = 'd' THEN survey_answers.answer END AS reason_2
FROM survey_answers
如何查询score_1 | reason_1 | score_2 | reason_2
----------------------------------------------
10 | NULL | NULL | NULL
NULL | foo | NULL | NULL
NULL | NULL | 9 | NULL
NULL | NULL | NULL | bar
2 | NULL | NULL | NULL
NULL | baz | NULL | NULL
NULL | NULL | 4 | NULL
NULL | NULL | NULL | zip
,以便将每个组折叠成一行?
答案 0 :(得分:1)
SQL表表示无序集。除非有列指定排序,否则没有排序。但是,您真正需要的不是排序,而是指定特定答案集的列。我们称之为responder_id
。
然后,您可以使用聚合:
SELECT sa.responder_id,
MAX(CASE WHEN sa.question_id = 'a' THEN sa.answer END) AS score_1,
MAX(CASE WHEN sa.question_id = 'b' THEN sa.answer END) AS reason_1,
MAX(CASE WHEN sa.question_id = 'c' THEN sa.answer END) AS score_2,
MAX(CASE WHEN sa.question_id = 'd' THEN sa.answer END) AS reason_2
FROM survey_answers sa
GROUP BY sa.reponder_id;