MySQL基于2列计数和分组结果

时间:2017-10-18 14:45:56

标签: mysql group-by

如果我在表answers中有以下数据:

+-------------------------------------------+
| forum_id | user_id | question_id | answer |
+-------------------------------------------+
| 1        | 1       | 1           | A      |
| 1        | 1       | 2           | B      |
| 1        | 2       | 1           | B      |
| 1        | 2       | 2           | B      |
| 1        | 3       | 1           | A      |
| 1        | 3       | 2           | B      |
| 2        | 1       | 1           | A      |
| 2        | 2       | 2           | A      |
+-------------------------------------------+

我如何选择答案的计数?要重新调整结果,例如:

+------------------------------+
| question_id | answer | count |
+------------------------------+
| 1           | A      | 2     |
| 1           | B      | 1     |
| 2           | A      | 3     |
| 2           | B      | 0     |
+------------------------------+

这就是我现在所拥有的。我知道它必须使用GROUP BY,但我很难回复预期的结果。

SELECT question_id, answer, COUNT(*)
FROM answers
WHERE forum_id = 1
GROUP BY question_id, answer

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT t.question_id, t.answer, COUNT(DISTINCT user_id)
FROM
(
  SELECT DISTINCT a.question_id, t.answer
  FROM answers as a, (SELECT 'A' AS answer UNION ALL SELECT 'B') AS t
) AS t
LEFT JOIN answers  AS a ON a.question_id = t.question_id
AND a.answer = t.answer and forum_id = 1
GROUP BY t.question_id, t.answer;

结果:

| question_id | answer | count |
|-------------|--------|-------|
|           1 |      A |     2 |
|           1 |      B |     1 |
|           2 |      A |     0 |
|           2 |      B |     3 |

请注意:

在你的样本数据中,B有2个问题2的条目,而A没有问题2的条目。当然所有论坛= 1,所以你的预期结果是不正确的,我认为我的是正确的。