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

后端 未结 5 1449
轮回少年
轮回少年 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条回答
  •  南方客
    南方客 (楼主)
    2020-12-02 02:06

    This is the MSSQL Version

    select o.*, q1.[Type of Surgery:], q2.[Month of Surgery:], q3.[Year of surgery:]
        , q4.[Current Ostomy System Brand:]
        , q5.[Degree of Satisfaction with the fit and comfort of your Current Ostomy System:]
    from (
        select distinct ordID, ordName + ' ' + ordLastName as [name] from dbo.Orders
    ) o
    left join (
        select *, a.[Answer] as [Type of Surgery:] from cart_survey cs
        left join dbo.survey_answers a on cs.answer_id = a.id
        where cs.question_id = 1
    ) q1 on o.ordID = q1.[order_id]
    left join (
        select *, a.[Answer] as [Month of Surgery:] from cart_survey cs
        left join dbo.survey_answers a on cs.answer_id = a.id
        where cs.question_id = 2
    ) q2 on o.ordID = q2.[order_id]
    left join (
        select *, a.[Answer] as [Year of surgery:] from cart_survey cs
        left join dbo.survey_answers a on cs.answer_id = a.id
        where cs.question_id = 3
    ) q3 on o.ordID = q3.[order_id]
    left join (
        select *, a.[Answer] as [Current Brand:] from cart_survey cs
        left join dbo.survey_answers a on cs.answer_id = a.id
        where cs.question_id = 4
    ) q4 on o.ordID = q4.[order_id]
    left join (
        select *, a.[Answer] as [Degree of Satisfaction:] from cart_survey cs
        left join dbo.survey_answers a on cs.answer_id = a.id
        where cs.question_id = 5
    ) q5 on o.ordID = q5.[order_id]
    

提交回复
热议问题