SQL按结果计数的顺序

时间:2019-11-09 18:26:30

标签: mysql sql database sql-order-by

我有一张数据如下的表:

Meal ID   |   Child    |  Fruit

1              Child A     Apple
2              Child B     Orange
3              Child A     Banana
4              Child A     Orange
5              Child C     Banana
6              Child A     Banana
7              Child C     Banana
8              Child A     Banana

,我需要根据所吃的水果(例如如果搜索查询是“香蕉”,结果将显示如下:

Banana Eaters (Highest to Lowest)

Child   |   Number of Bananas eaten

Child A     3
Child C     1

我将从:

开始
 $sql = "SELECT * FROM meals WHERE Fruit = 'Banana'";

但是我该如何将吃香蕉的独特个体作为自己的条目,然后按食用最多的香蕉排序结果?

4 个答案:

答案 0 :(得分:1)

按孩子分组并使用条件聚合:

select child, sum(fruit = 'Banana') `Number of Bananas eaten`
from meals
group by child
order by `Number of Bananas eaten` desc 

如果要排除没有香蕉的孩子:

select child, sum(fruit = 'Banana') `Number of Bananas eaten`
from meals
group by child
having `Number of Bananas eaten` > 0
order by `Number of Bananas eaten` desc 

请参见demo

答案 1 :(得分:1)

用例何时

select child,sum(case when Fruit='Banana' then 1 else 0 end) as bananaeaten
from meals
group by child
order by bananaeaten desc

答案 2 :(得分:1)

select Child, count(*) as 'Number of bananas eaten' from meals
where Fruit = 'Banana'
group by Child
order by count(*) desc

答案 3 :(得分:0)

如果您不想看到“孩子B”,请在汇总之前进行过滤:

select Child, count(*) as num_bananas
from meals
where Fruit = 'Banana'
group by Child
order by count(*) desc;