当前查询:
SELECT order_id AS OrderNumber, ordName, ordLastName, question, answer
FROM cart_survey
JOIN orders
ON cart_survey.order_id=orders.ordID
JOIN survey_answers
ON survey_answers.id=cart_survey.answer_id
JOIN survey_questions
ON survey_questions.id=cart_survey.question_id
Run Code Online (Sandbox Code Playgroud)
结果:
OrderNumber ordName ordLastName question answer 8591 Larry Marshburn Type of Surgery: Colostomy 8591 Larry Marshburn Month of Surgery: 2 8591 Larry Marshburn Year of surgery: 2010 8591 Larry Marshburn Current Ostomy System Brand: ConvaTec 8591 Larry Marshburn Degree of Satisfaction: Somewhat Satisfied 8593 Melvin Belcher Type of Surgery: Urostomy 8593 Melvin Belcher Month of Surgery: 9 8593 Melvin Belcher Year of surgery: 2010 8593 Melvin Belcher Current Ostomy System Brand: ConvaTec 8593 Melvin Belcher Degree of Satisfaction: Very Satisfied
如何正确查询表以提取看起来像这样的结果?单行上的姓名和姓氏以及每列的列和答案的问题.
期望的结果
OrderNumber ordName ordLastName "Type of Surgery" "Month of Surgery" "Year of Surgery" etc. 8591 Larry Marshbourn Colostomy 2 2010 8593 Melvin Belcher Urostomy 9 2010
发布的答案有效但笨拙且缓慢.你可以做我称之为并行聚合的事情:
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
Run Code Online (Sandbox Code Playgroud)
这将通过表而不是三个,并且非常短.它不是一个完整的演练,但您可以根据您的需求调整概念.