本教程将向您展示如何使用sql count函数来获取组中的项目数。
sql count函数是一个聚合函数,它返回符合条件行数。 可以使用select语句中的count函数来获取员工数量,每个部门的员工数量,指定工作岗位的员工数量等。
以下是sql count函数的语法:
countc ([all | distinct] expression);
count函数的结果取决于传递给它的参数。
默认情况下,count函数使用all关键字,无论是否指定它。 all关键字表示考虑组中的所有项目,包括重复值。 例如,如果有一个数据集合(1,2,3,3,4,4)并应用count函数,则结果为6。
如果明确指定distinct关键字,则仅考虑唯一的非null值。 如果将count函数应用于数据集(1,2,3,3,4,4),则count函数返回4。
另一种形式的count函数接受星号(*)作为参数如下:
count(*)
count(*)函数返回表中的行数,包括包含null值的行。
下面举一些例子来看看count函数是如何工作的。将使用示例数据库中的employees表进行演示。
2.1. sql count(*)示例
要获取employees表中的行数,请使用count(*)函数,如下所示:
select
count(*)
from
employees;
执行上面查询语句,得到以下结果:
+----------+
| count(*) |
+----------+
| 40 |
+----------+
1 row in set
要查找在部门id为 6 中工作的员工数量,请将where子句添加到查询中,如下所示:
select
count(*)
from
employees
where
department_id = 6;
执行上面查询语句,得到以下结果:
+----------+
| count(*) |
+----------+
| 5 |
+----------+
1 row in set
同样,要查询工作岗位id为9的员工数量,请使用以下语句:
select
count(*)
from
employees
where
job_id = 9;
执行上面查询语句,得到以下结果:
+----------+
| count(*) |
+----------+
| 5 |
+----------+
1 row in set
2.2. sql count与group by子句示例
要查找每个部门的员工数,请使用count和group by子句,如下所示:
要在结果集中获取部门名称,需要将employees表与departments表内连接,如下所示:
select
e.department_id,
department_name,
count(*)
from
employees e
inner join departments d on d.department_id = e.department_id
group by
e.department_id;
执行上面查询语句,得到以下结果:
2.3. sql count(*)带有order by子句的示例
可以在count(*)函数使用order by子句对每个组的行数进行排序。 例如,以下语句获取每个部门的员工数,并根据员工数按降序对结果集进行排序。
select
e.department_id,
department_name,
count(*)
from
employees e
inner join departments d on d.department_id = e.department_id
group by
e.department_id
order by
count(*) desc;
执行上面查询语句,得到以下结果:
2.4. sql count带有having子句的示例
要按count(*)函数的结果过滤分组,需要在count(*)函数使用having子句。
例如,以下语句获取部门及其员工数量。 此外,它仅选择员工人数大于5的部门。
select
e.department_id,
department_name,
count(*)
from
employees e
inner join departments d on d.department_id = e.department_id
group by
e.department_id
having
count(*) > 5
order by
count(*) desc;
执行上面查询语句,得到以下结果:
2.5. sql count(distinct表达式)示例
要获取employees表中的工作岗位数,请将count函数应用于job_id列,如下所示:
select
count(job_id)
from
employees;
执行上面示例代码,得到以下结果:
+---------------+
| count(job_id) |
+---------------+
| 40 |
+---------------+
1 row in set
上面查询中返回结果为:40,其中包含重复的工作岗位id。 我们希望找出工作岗位数量,则要删除重复项,那么要将distinct关键字添加到count函数,如下所示:
select
count(distinct job_id)
from
employees;
+------------------------+
| count(distinct job_id) |
+------------------------+
| 19 |
+------------------------+
1 row in set
可以使用count distinct获取经理数量,如下查询:
select
count(distinct manager_id)
from
employees;
+----------------------------+
| count(distinct manager_id) |
+----------------------------+
| 10 |
+----------------------------+
1 row in set
注意: 主席没有经理。
在本教程中,您学习了应用sql count函数以获取组中行数的各种方法。