我正在使用max函数将行转换为列,并且在子查询中使用它之前,它运行良好。
情况:[请以超链接显示图片]我总共有三个问题供客户回答,他们的回答将从数据库中提取。但是,对于第一个问题,客户可以选择1-10。10是指自由文本,将存储在问题= 2的答案中。
但是,我想排除来自客户的自由文本输入,并将其提取到列中。不得不说,我将拥有三列:Response_1,Response_2和Response_3。当客户为问题= 1选择10时,问题= 3的答案将存储在Response_2中,而问题= 4的答案将存储在Response_3中。
我的尝试如下:
select customer_ID
max( CASE WHEN Question = 1 THEN Answer END) Response_1,
max( CASE WHEN Question = 1 AND Answer != 10 THEN
( select
max( CASE WHEN Question = 2 THEN Answer END)
from t_question_answer)
ELSE
( select
max( CASE WHEN Question = 3 THEN Answer END)
from t_question_answer)
END)
) Response_2
from t_question_answer
group by customer_ID
当涉及到为customer_2提取的数据时,结果出错了,我认为在子查询中,它再次在整个数据中寻找最大值,而不是指定相同的客户。
答案 0 :(得分:0)
您需要在条件聚合中使用更多条件逻辑:
select customer_ID
max(CASE WHEN Question = 1 THEN Answer END) Response_1,
(case when max(case when question = 1 and answer = 10 then 1 else 0 end) > 0
then max( CASE WHEN Question = 3 THEN Answer END)
else max( CASE WHEN Question = 2 THEN Answer END)
end) as Response_2,
(case when max(case when question = 1 and answer = 10 then 1 else 0 end) > 0
then max( CASE WHEN Question = 4 THEN Answer END)
else max( CASE WHEN Question = 3 THEN Answer END)
end) as Response_3
from t_question_answer
group by customer_ID