0

这是我的表:

这是我的桌子

我正在运行这个查询,

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

我得到的结果是

在此处输入图像描述

如果与这样的所有者不匹配,是否可以将其他水果项目设为 0,

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

非常感谢对我的查询进行一些修改。谢谢

4

2 回答 2

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

或使用IFMySQL

SELECT  fruits, 
        SUM(IF(owner = 'bill',1,0)) as `count `
FROM     meva 
GROUP BY fruits 
ORDER BY fruits
于 2013-01-15T07:01:31.703 回答
1

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

SELECT  fruits, 
        SUM(Coalesce(owner='bill',0)) as counts
FROM     meva 
GROUP BY fruits 
ORDER BY fruits
;
于 2013-01-15T07:27:06.730 回答