mysql - 如何编写 COUNT(DISTINCT()) 查询?

标签 mysql sql postgresql sqlite

请帮我解决这个问题。

我有一个学生表,它看起来像:

*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,因为存在三个不同的值 123 .

关于mysql - 如何编写 COUNT(DISTINCT()) 查询?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32923762/

相关文章:

mysql - mysql查询问题中不同用户的两个日期之间的总和记录

mysql - 获取连接 2 个表的行数

Postgresql 10 逻辑复制 MultiMaster

sql - 按状态计算所有行

php - 使用 mysql_real_escape_string() 时访问被拒绝错误

mysql - Active Record (MYSQL) - 从多个列中选择不同的 id

php - 重复使用关键字进行搜索

sql - oracle 中不同的逗号分隔值

sql - 在数据中查找指定模式--Hive

sql - 使用 CTE 的结果进行更新