T Sql 简明教程
T-SQL - DISTINCT Clause
MS SQL Server DISTINCT 关键字与 SELECT 语句一起使用,以消除所有重复的记录并仅获取唯一的记录。
The MS SQL Server DISTINCT keyword is used in conjunction with SELECT statement to eliminate all the duplicate records and fetching only unique records.
在表中,你可能会遇到重复记录的情况。在获取这些记录时,只获取唯一记录比获取重复记录更有意义。
There may be a situation when you have multiple duplicate records in a table. While fetching such records, it makes more sense to fetch only unique records instead of fetching duplicate records.
Syntax
以下是 DISTINCT 关键字消除重复记录的基本语法。
Following is the basic syntax of DISTINCT keyword to eliminate duplicate records.
SELECT DISTINCT column1, column2,.....columnN
FROM table_name
WHERE [condition]
Example
可以将 CUSTOMERS 表视为包含以下记录。
Consider the CUSTOMERS table having the following records.
ID NAME AGE ADDRESS SALARY
1 Ramesh 32 Ahmedabad 2000.00
2 Khilan 25 Delhi 1500.00
3 kaushik 23 Kota 2000.00
4 Chaitali 25 Mumbai 6500.00
5 Hardik 27 Bhopal 8500.00
6 Komal 22 MP 4500.00
7 Muffy 24 Indore 10000.00
让我们看看 다음 SELECT 查询如何返回重复的薪资记录。
Let us see how the following SELECT query returns duplicate salary records.
SELECT SALARY FROM CUSTOMERS
ORDER BY SALARY
上述命令将产生以下输出,其中薪资 2000 出现两次,这是原始表中的重复记录。
The above command will produce the following output where salary 2000 comes twice which is a duplicate record from the original table.
SALARY
1500.00
2000.00
2000.00
4500.00
6500.00
8500.00
10000.00
现在,让我们对上述 SELECT 查询使用 DISTINCT 关键字并查看结果。
Let us now use DISTINCT keyword with the above SELECT query and see the result.
SELECT DISTINCT SALARY FROM CUSTOMERS
ORDER BY SALARY
上述命令会产生以下输出,其中我们没有任何重复项。
The above command produces the following output where we do not have any duplicate entry.
SALARY
1500.00
2000.00
4500.00
6500.00
8500.00
10000.00