在列中计算不同的值,如果在Where子句中找不到则返回零

时间:2013-01-15 06:59:39

标签: mysql sql select

这是我的表:

This is my table

我正在运行此查询,

SELECT fruits,COUNT(*) as count FROM meva where owner = 'bill' GROUP BY fruits ORDER BY count 

我的结果是

enter image description here

如果没有像这样的所有者匹配,是否有可能将其他水果项目设为0,

Fruit   | count
Apple   ,   2
Mango   ,   0
Banana  ,   0
Strawberry ,0
Appricot,   0
Alfonso ,   0

我非常感谢我的查询中的一点修改。 感谢

2 个答案:

答案 0 :(得分:1)

使用SUM()CASE

SELECT  fruits, 
        SUM(CASE WHEN owner = 'bill' THEN 1 ELSE 0 END) as `count `
FROM     meva 
GROUP BY fruits 
ORDER BY fruits

或使用IF仅在MySQL

SELECT  fruits, 
        SUM(IF(owner = 'bill',1,0)) as `count `
FROM     meva 
GROUP BY fruits 
ORDER BY fruits

答案 1 :(得分:1)

是的,那里有一个很好的答案。你也可以试试这个!

SELECT  fruits, 
        SUM(Coalesce(owner='bill',0)) as counts
FROM     meva 
GROUP BY fruits 
ORDER BY fruits
;