繁体   English   中英

使用max查询和子查询的SQL / PL行到列

[英]SQL/PL Rows to Columns using max query with Sub-query

我正在使用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提取的数据时,结果出错了,我认为在子查询中,它再次在整个数据中寻找最大值,而不是指定相同的客户。

点击此图片以获得更好的插图

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM