Poor Man's SQL Pivot. List Questions as Columns and Answers per User in one row

后端 未结 5 1459
轮回少年
轮回少年 2020-12-02 01:44

Current query:

SELECT order_id AS OrderNumber, ordName, ordLastName, question, answer 
FROM cart_survey 
JOIN orders 
    ON cart_surv         


        
5条回答
  •  旧时难觅i
    2020-12-02 01:57

    The posted answers work but are clumsy and slow. You can do what I call parallel aggregation:

    SELECT
         ID,
         SUM(case when question_id = 1 then 1 else 0 end) as sum1,
         SUM(case when question_id = 2 then 1 else 0 end) as sum2,
         SUM(case when question_id = 3 then 1 else 0 end) as sum3
    GROUP BY ID
    

    This will do one pass over the table instead of three and is very short. It is not a complete walk-through but you can surely adapt the concept to your needs.

提交回复
热议问题