简体   繁体   English

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

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

I was using max function to convert from rows to column and before using it in sub-query, it works well. 我正在使用max函数将行转换为列,并且在子查询中使用它之前,它运行良好。

Situation: [Please refer to the picture as hyperlinked] I have a total of three questions for customer to answer and their responses will be extracted from the database. 情况:[请以超链接显示图片]我总共有三个问题供客户回答,他们的回答将从数据库中提取。 However, for the first question, customer is allowed to choose from 1 - 10. 10 refers to free text and will be stored in answer for Question = 2. 但是,对于第一个问题,客户可以选择1-10。10指自由文本,将存储在问题= 2的答案中。

However, I would like to exclude free text input from the customer and for the extraction to be in column. 但是,我想排除来自客户的自由文本输入,并将提取内容包含在专栏中。 Having to say that I will be having three columns: Response_1, Response_2 and Response_3. 不得不说,我将拥有三列:Response_1,Response_2和Response_3。 When customer choose 10 for Question = 1, the answer for Question = 3 will be stored in Response_2 while answer for Question = 4 in Response_3. 当客户为问题= 1选择10时,问题= 3的答案将存储在Response_2中,而问题= 4的答案将存储在Response_3中。

My attempt is as follow: 我的尝试如下:

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

The result went wrong when it comes to the data extracted for customer_2 where I think in the sub-query, it looks for the maximum value in the whole data again instead of specifying the same customer. 当涉及到为customer_2提取的数据时,结果出错了,我认为在子查询中,它再次在整个数据中寻找最大值,而不是指定相同的客户。

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

You need more conditional logic in your conditional aggregation: 您的条件聚合中需要更多的条件逻辑:

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