mysql重复计数和总计

时间:2018-02-09 14:48:14

标签: mysql sql

我有一张像这样的桌子,

name food  
A    Apple  
B    Banana  
A    Banana  
C    Apple

我想要不同数量的水果及其总重复数。

food  count

2               4


SELECT food, COUNT(food) AS cnt
FROM table
GROUP BY food
HAVING (cnt > 1)

给出了每种水果的总数。如何将此查询修改为我想要的结果

2 个答案:

答案 0 :(得分:1)

SELECT count(distinct food), COUNT(*) AS cnt
from tablename

答案 1 :(得分:0)

使用额外的聚合层:

SELECT COUNT(*) as num_foods, SUM(cnt) as num_rows
FROM (SELECT food, COUNT(food) AS cnt
      FROM table
      GROUP BY food
     ) f;