合并计数等于0组

时间:2017-05-18 13:46:36

标签: sql postgresql

晚上好!我如何COALESCECOUNT(*)查询分组?

SELECT categories.name, COALESCE(COUNT(*), 0) as total FROM questions
  INNER JOIN categories
    ON questions.categoryid = categories.categoryid
GROUP BY name
ORDER BY total DESC;

我阅读了文档,这是执行此操作的主要解决方案,但它没有使用total = 0返回类别。

亲切的问候

1 个答案:

答案 0 :(得分:1)

count()的返回值无效,因此您不需要coalesce

你可能试着这个吗?

SELECT categories.name, COUNT(questions.categoryid) as total 
FROM questions
RIGHT OUTER JOIN categories
    ON questions.categoryid = categories.categoryid
GROUP BY name
ORDER BY total DESC;