使用`count`获取`group by`上值为0的列

时间:2019-05-15 13:43:48

标签: mysql sql

我正在使用此查询来获取按cmp2字段分组的行数,但是我需要为每个cmp2获取一列,即使其总和为0。我不能这样:

SELECT CMP2, COALESCE(count(*), 0) as count 
FROM datos_con851_0,
     datos_con851_1  
WHERE datos_con851_0.REGISTRO = datos_con851_1.REGISTRO 
  AND SPEEDER = 1
GROUP BY CMP2;

1 个答案:

答案 0 :(得分:0)

您想要一个left join,大概是这样的:

SELECT d0.CMP2, count(d1.REGISTRO) as count 
FROM datos_con851_0 d0 left join
     datos_con851_1 d1
     on d0.REGISTRO = d1.REGISTRO AND
        d1.SPEEDER = 1  -- just guess this comes from `d1`
GROUP BY d0.CMP2;