SQL COUNT()

SQL COUNT() 函数返回查询返回的记录数。

示例

-- returns the count of rows in the Orders table

SELECT COUNT(*)
FROM Orders;

这里,上面的 SQL 命令返回 Orders 表中的行数。


COUNT() 语法

SELECT COUNT(*)
FROM table;

这里,

  • COUNT() 是计算表中行数的函数。
  • table 是表的名称。

示例:SQL COUNT()

--returns the number of rows in the Customers table

SELECT COUNT(*)
FROM Customers;

这里,上面的 SQL 命令计算并返回 Customers 表中的行数。

How to use COUNT() Function in SQL
示例:SQL COUNT() 函数

带 COUNT() 的别名

可以使用 AS 关键字为输出字段指定自定义名称。例如,

--return the count of rows from the customers table as total_customers

SELECT COUNT(*) AS total_customers
FROM Customers;

这里,结果集中字段名 COUNT(*)total_customers 替换。

How to use alias in SQL with COUNT() function
示例:SQL COUNT() 带别名

示例:指定要计数的列

我们也可以在 COUNT() 中指定列名,只计算该特定列中的行。

让我们看一个例子。

--returns the count of non-null values in the age column

SELECT COUNT(age)
FROM Customers;

这里,上面的 SQL 查询返回 age 列中非空值的数量。

SQL COUNT() Using a Column
使用列的 SQL COUNT()

这里,当我们指定列名而不是 * 时,NULL 值不包含在计数中。


带 WHERE 的 COUNT()

我们可以使用带 WHERECOUNT() 来计算匹配给定值的行。

-- count of customers who live in the UK

SELECT COUNT(country)
FROM Customers
WHERE country = 'UK';

这里,SQL 命令返回国家为 UK 的客户数量。

How to use COUNT() with WHERE in SQL
示例:带 WHERE 的 SQL COUNT() 函数

带 DISTINCT 的 COUNT()

如果我们需要计算唯一行的数量,可以使用带 DISTINCT 子句的 COUNT() 函数。例如,

-- count the unique countries in Customers table

SELECT COUNT(DISTINCT country)
FROM Customers;

这里,SQL 命令返回唯一国家的数量。

DISTINCT and COUNT used together to count unique values
示例:计算唯一国家

更多关于 SQL COUNT() 的信息

带 GROUP BY 的 COUNT()

COUNT() 函数可以与 GROUP BY 子句一起使用,以计算具有相似值的行。例如,

-- count the number of customers in each country

SELECT country, COUNT(*) AS customers
FROM Customers
GROUP BY country;

这里,SQL 命令返回每个国家/地区的客户数量。

How to use COUNT() Function with GROUP BY in SQL
示例:带 GROUP BY 的 SQL COUNT() 函数
带 HAVING 子句的 COUNT()

我们可以像这样使用带 HAVING 子句的 COUNT()

--count the number of rows by country and return the results for count greater than one

SELECT COUNT(customer_id), country
FROM Customers
GROUP BY country
HAVING COUNT(customer_id) > 1;

这里,SQL 命令

  • country 分组计算行数
  • 如果它们的计数大于1,则返回结果集

另请阅读

在结束之前,让我们测试一下您对 SQL COUNT() 的知识!您能解决以下挑战吗?

挑战

编写一个 SQL 查询,找出注册课程最多的用户。

假设您有一个名为 Courses 的表。该表的架构如下:

课程

列名

数据类型

user_id

int

course_completed

varchar(100)

Programiz 的营销团队渴望找出完成课程最多的用户。


您的任务是编写一个 SQL 查询,找出注册并完成课程数量最多的用户,以及他们完成的课程总数。

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战