如何在选择时根据它们的值将一列分成多列?

How can I seperate one column into multiple columns depending on their value when selecting it?

我有一个名为 assignment_answers 的 table,它具有以下属性: assignment_answers_id,question_id 和订单。 order 是一个属性,可以取 0 到 9 之间的值。 我希望每个值都可以显示在不同的列中。例如,当订单值为 0 时,我希望它显示在名为 number0 的列中。当它的值为 1 时,我希望它显示在名为 number1 的列中。

有人可以帮我吗?到目前为止,我已经尝试过了,但它不起作用:

SELECT (CASE WHEN assessment_answers.order = 0 
             THEN(
              select aq.order as number0
              from assessment_answers)
              END)
       (CASE WHEN assessment_answers.order = 1 
             THEN(
              select aq.order as number1
              from assessment_answers)
              END)
FROM assessment_answers

我收到一条错误消息: 错误:“(”处或附近的语法错误 第 6 行:(当 assessment_questions."order" = 1

时的情况

示例数据

assignment_answers_id     question_id    order
 1                            1           0
 2                            1           0
 3                            2           1

期望的输出:

assignment_answers_id     question_id    order0  order1
 1                            1           0       null
 2                            1           0       null
 3                            2           null     1

这是你想要的吗?

select (aa.order = 0)::int as order_0, 
       (aa.order = 1)::int as order_1, 
       (aa.order = 2)::int as order_2, 
       . . .
from  assessment_answers aa;

你可以尝试使用普通的CASE WHEN

查询 1:

SELECT assignment_answers_id,
       question_id,
       (CASE WHEN order = 0 THEN order END) order0,
       (CASE WHEN order = 1 THEN order END) order1
FROM assessment_answers

Results:

| assignment_answers_id | question_id | order0 | order1 |
|-----------------------|-------------|--------|--------|
|                     1 |           1 |      0 | (null) |
|                     2 |           1 |      0 | (null) |
|                     3 |           2 | (null) |      1 |