这是我的第一个问题所以我希望我不要搞砸它。
这是我帮助我解释的一个SQL小提琴:http://sqlfiddle.com/#!9/7f2b5c/7
我们有问题,答案,question_types和answer_types。
我想知道每个问题,有多少人回答了每个answer_type以及有多少人回答了这个问题,但是我无法得到总数。
这就是我得到的:
id | fk_question_type | description | num | value | total
1 | 1 | How was the breakfast? | 0 | Bad | 0
1 | 1 | How was the breakfast? | 1 | Good | 1
1 | 1 | How was the breakfast? | 0 | Indifferent| 0
1 | 1 | How was the breakfast? | 2 | Very good | 2
2 | 1 | How was the lunch? | 0 | Bad | 0
2 | 1 | How was the lunch? | 1 | Good | 1
2 | 1 | How was the lunch? | 0 | Indifferent| 1
2 | 1 | How was the lunch? | 1 | Very good | 1
这就是我想要的:
id | fk_question_type | description | num | value | total
1 | 1 | How was the breakfast? | 0 | Bad | 3
1 | 1 | How was the breakfast? | 1 | Good | 3
1 | 1 | How was the breakfast? | 0 | Indifferent| 3
1 | 1 | How was the breakfast? | 2 | Very good | 3
2 | 1 | How was the lunch? | 0 | Bad | 2
2 | 1 | How was the lunch? | 1 | Good | 2
2 | 1 | How was the lunch? | 0 | Indifferent| 2
2 | 1 | How was the lunch? | 1 | Very good | 2
我正在尝试的查询:
SELECT id, fk_question_type, description, num, value, SUM(num) AS totalAnswers
FROM (
(SELECT q.id, q.fk_question_type, q.description, COUNT(a.id) AS num, at.value
FROM answer a
LEFT JOIN question q ON a.`fk_question`=q.`id`
LEFT JOIN answer_type at ON at.id = a.`fk_answer_type`
GROUP BY q.id, at.id ORDER BY q.id, at.id)
UNION ALL
(SELECT q.id, q.fk_question_type, q.description, 0 AS num, at.value
FROM answer a
LEFT JOIN question q ON a.`fk_question`=q.`id`
LEFT JOIN answer_type at ON at.fk_question_type=q.fk_question_type
GROUP BY q.id, at.id ORDER BY q.id, at.id)
) AS T
WHERE fk_question_type = 1
GROUP BY id, value ORDER BY id
如何在保留其他列的同时对具有相同id的行的num进行求和?
答案 0 :(得分:0)
使用子查询获取每个id
的总计,并将其与获取每值行的查询相连接。
在外部查询中,您应该使用SUM(num)
或MAX(num)
来合并num
中两个查询的UNION
值。
SELECT T.id, fk_question_type, description, SUM(num) AS num, value, T2.totalAnswers
FROM (
(SELECT q.id, q.fk_question_type, q.description, COUNT(a.id) AS num, at.value
FROM answer a
LEFT JOIN question q ON a.`fk_question`=q.`id`
LEFT JOIN answer_type at ON at.id = a.`fk_answer_type`
GROUP BY q.id, at.id ORDER BY q.id, at.id)
UNION ALL
(SELECT q.id, q.fk_question_type, q.description, 0 AS num, at.value
FROM answer a
LEFT JOIN question q ON a.`fk_question`=q.`id`
LEFT JOIN answer_type at ON at.fk_question_type=q.fk_question_type
GROUP BY q.id, at.id ORDER BY q.id, at.id)
) AS T
JOIN (SELECT q.id, COUNT(*) AS totalAnswers
FROM answer a
LEFT JOIN question q ON a.`fk_question`=q.`id`
LEFT JOIN answer_type at ON at.id = a.`fk_answer_type`
GROUP BY q.id) AS t2 ON T.id = T2.id
WHERE fk_question_type = 1
GROUP BY T.id, value