使用连接将行转换为postgresql中的列

时间:2015-07-24 16:44:34

标签: postgresql

所有。我和this one有一个非常相似的问题。我正在尝试将行转换为结果中的列,但我还需要将几个表连接在一起。我开始掌握如何在一个表中执行此操作,但我不知道如何使用连接来完成相同的操作。

我有3张桌子 - 测试,问题和答案。测试有问题。问题有答案。到目前为止非常明显。我需要为某个测试提取问题和答案列表,但我希望它以某种格式。 (我没有设置这些 - 这是我必须使用的。)

就像我说的,这与将行移动到列的另一篇文章非常相似,但我不确定如何将连接与它结合起来。

这是表结构:

TEST
----------
id
task_id
name

QUESTION
----------
id
test_id
text
correctanswer_id

ANSWER
----------
id
question_id
text

这就是我现在所拥有的以及从中得到的东西:

-- select all review questions for a specific video
select t.id as "testid", q.id as "questionid", q.text as "questiontext",
    a.id as "answerid", a.text as "answertext"
from "Question" q
    inner join "Answer" a on a.question_id = q.id
    inner join "Test" t on t.id = q.test_id
where t.test_id = 100

+--------+------------+--------------+----------+------------+
| testid | questionid | questiontext | answerid | answertext |
+--------+------------+--------------+----------+------------+
| 100    | 200        | 'Question 1' | 300      | 'Answer 1' |
| 100    | 200        | 'Question 1' | 301      | 'Answer 2' |
| 100    | 200        | 'Question 1' | 302      | 'Answer 3' |
| 100    | 200        | 'Question 1' | 303      | 'Answer 4' |
| 100    | 201        | 'Question 2' | 304      | 'Answer 1' |
| 100    | 201        | 'Question 2' | 305      | 'Answer 2' |
| 100    | 201        | 'Question 2' | 306      | 'Answer 3' |
| 100    | 201        | 'Question 2' | 307      | 'Answer 4' |
+--------+------------+--------------+----------+------------+

这就是我需要的东西:

+--------+------------+--------------+-----------+-------------+-----------+-------------+-----------+-------------+-----------+-------------+------------------+
| testid | questionid | questiontext | answerid1 | answertext1 | answerid2 | answertext2 | answerid3 | answertext3 | answerid4 | answertext4 | correctanswer_id |
+--------+------------+--------------+-----------+-------------+-----------+-------------+-----------+-------------+-----------+-------------+------------------+
| 100    | 200        | 'Question 1' | 300       | 'Answer 1'  | 301       | 'Answer 2'  | 302       | 'Answer 3'  | 303       | 'Answer 4'  | 301              |
| 100    | 201        | 'Question 2' | 304       | 'Answer 1'  | 305       | 'Answer 2'  | 306       | 'Answer 3'  | 307       | 'Answer 4'  | 307              |
+--------+------------+--------------+-----------+-------------+-----------+-------------+-----------+-------------+-----------+-------------+------------------+

1 个答案:

答案 0 :(得分:1)

您是否尝试在查询中使用Case语句?

select t.id as "testid", q.id as "questionid", q.text as "questiontext",
    a.id as "answerid", a.text as "answertext", CASE WHEN answertext= 'Answer 1' then answertext as answertext1
from "Question" q
    inner join "Answer" a on a.question_id = q.id
    inner join "Test" t on t.id = q.test_id
where t.test_id = 100

这是一个更详细的链接: http://www.postgresql.org/docs/7.4/static/functions-conditional.html