如何使用具有不同值的COUNT(*)函数?

时间:2012-10-30 04:36:20

标签: mysql sql count group-by

例如,我的表格中包含geographychildren等列。我需要计算每个childrens中有多少country

我只能做出这样的事情:

SELECT geography, COUNT( * ) 
FROM table1
GROUP BY children
ORDER BY geography

嗯,我有例如:

Canada John
Canada John
Canada Peter

我需要来自加拿大的结果有2 children 但如果我要group by children,结果就是:

Canada 2
Canada 1

如果group by geography那么,

Canada 3

3 个答案:

答案 0 :(得分:4)

这里不需要

SUM。您唯一要做的就是按geography分组。

SELECT geography, COUNT(DISTINCT children) totalCount
FROM table1
GROUP BY geography
ORDER BY geography

答案 1 :(得分:1)

如果您只需要计算组中的唯一值,则可以使用COUNT(DISTINCT expr)

SELECT geography, COUNT(DISTINCT children) 
FROM table1
GROUP BY geography
ORDER BY geography

答案 2 :(得分:0)

如果地理位置是国家/地区字段,则必须将其添加到分组依据中。

SELECT geography, COUNT(children)
FROM table1
GROUP BY geography
ORDER BY geography