请帮我解决这个问题。
我有一个学生表,它看起来像:
*id, name, surname, year, course*
1, John, Johnson, 3, Economy
2, Lara, Croft, 2, Biology
3, Mark, Jones, 3, Economy
4, Jim, Smith, 1, IT
5, Sarah, Kennedy, 1, IT
6, Matt, Damon, 3, Economy
并希望将所有类(class)的学生人数作为结果集,例如:
*course, count*
Economy, 3
IT, 2
Biology, 1
最佳答案
你不会为此使用 count(distinct ...)
,只需在类(class)中分组并使用 count()
:
select
cource,
count(*)
from
Students
group by
cource
order by
cource
如果您想在一个组中进行不同的计数,使用 count(distinct ...)
很有用,例如计算 year
的不同值(在所有记录的隐式组):
select
count(distinct year)
from
Students
这将为您提供结果 3
,因为存在三个不同的值 1
、2
和 3
.
关于mysql - 如何编写 COUNT(DISTINCT()) 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32923762/