sql计数
This article explores SQL Count Distinct operator for eliminating the duplicate rows in the result set.
本文探讨了SQL Count Distinct运算符,该运算符用于消除结果集中的重复行。
A developer needs to get data from a SQL table with multiple conditions. Sometimes, we want to get all rows in a table but eliminate the available NULL values. Suppose we want to get distinct customer records that have placed an order last year.
开发人员需要从具有多个条件SQL表中获取数据。 有时,我们希望获取表中的所有行,但要消除可用的NULL值。 假设我们要获得去年下订单的不同客户记录。
Let’s go ahead and have a quick overview of SQL Count Function.
让我们继续快速浏览一下SQL Count Function。
SQL计数功能 (SQL Count Function)
We use SQL Count aggregate function to get the number of rows in the output. Suppose we have a product table that holds records for all products sold by a company. We want to know the count of products sold during the last quarter. We can use SQL Count Function to return the number of rows in the specified condition.
我们使用SQL Count聚合函数来获取输出中的行数。 假设我们有一个产品表,其中包含公司出售的所有产品的记录。 我们想知道上一季度销售的产品数量。 我们可以使用SQL Count Function返回指定条件下的行数。
The syntax of the SQL COUNT function:
COUNT ([ALL | DISTINCT] expression);
SQL COUNT函数的语法 :
COUNT([ALL | DISTINCT]表达式);
By default, SQL Server Count Function uses All keyword. It means that SQL Server counts all records in a table. It also includes the rows having duplicate values as well.
默认情况下,SQL Server计数功能使用All关键字。 这意味着SQL Server对表中的所有记录进行计数。 它还包括具有重复值的行。
Let’s create a sample table and insert few records in it.
让我们创建一个示例表并在其中插入一些记录。
CREATE TABLE ##TestTable (Id int identity(1,1), Col1 char(1) NULL);
INSERT INTO ##TestTable VALUES ('A');
INSERT INTO ##TestTable VALUES ('A');
INSERT INTO ##TestTable VALUES ('B');
INSERT INTO ##TestTable VALUES ('B');
INSERT INTO ##TestTable VALUES (NULL);
INSERT INTO ##TestTable VALUES (NULL);
In this table, we have duplicate values and NULL values as well.
在此表中,我们还有重复的值和NULL值。
In the following screenshot, we can note that:
在以下屏幕截图中,我们可以注意到:
- Count (*) includes duplicate values as well as NULL values 计数(*)包括重复值以及NULL值
- Count (Col1) includes duplicate values but does not include NULL values 计数(Col1)包含重复值,但不包含NULL值
Suppose we want to know the distinct values available in the table. We can use SQL COUNT DISTINCT to do so.
假设我们想知道表中可用的不同值。 我们可以使用SQL COUNT DISTINCT来做到这一点。
Select count(DISTINCT COL1)
from ##TestTable
In the following o