首页 > 解决方案 > 使用带有子查询的最大查询的 SQL/PL 行到列

问题描述

我使用 max 函数将行转换为列,在子查询中使用它之前,它运行良好。

情况:[请参考图片为超链接]我一共有三个问题要客户回答,他们的回答将从数据库中提取。但是,对于第一个问题,允许客户从 1 - 10 中进行选择。10 是指自由文本,将存储在 Question = 2 的答案中。

但是,我想排除客户的自由文本输入,并将提取放在列中。不得不说我将有三列:Response_1、Response_2 和 Response_3。当客户为 Question = 1 选择 10 时,Question = 3 的答案将存储在 Response_2 中,而 Question = 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 提取的数据时,结果出错了,我认为在子查询中,它再次在整个数据中查找最大值,而不是指定同一个客户。

单击此图片以获得更好的说明

标签: sql

解决方案


您在条件聚合中需要更多条件逻辑:

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

推荐阅读