简体   繁体   中英

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.

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.

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. 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.

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.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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