sql去重distinct的用法(数据库distinct去重查询)

在SQL查询中,我们经常需要对结果进行去重操作,以消除重复的记录。而在数据库中,我们可以使用DISTINCT关键字来实现这个目的。DISTINCT关键字能够返回唯一不重复的值,让我们能够轻松地获取去重后的数据集。

distinct关键字的作用是去除查询结果中的重复记录,只保留不同的值,可以用在select语句中,也可以用在聚合函数中,如count、sum、avg等。

sql去重distinct用法

sql去重distinct的用法(数据库distinct去重查询)

distinct去重的语法格式如下:

select distinct 列名 from 表名;

或者

select 聚合函数(distinct 列名) from 表名;

举例说明:

假设有一个学生表student,包含以下字段和数据:

| id | name | gender | age |
|----|------|--------|-----|
| 1 | 张三 | 男 | 18 |
| 2 | 李四 | 女 | 19 |
| 3 | 王五 | 男 | 20 |
| 4 | 赵六 | 女 | 18 |
| 5 | 张三 | 男 | 21 |

1、如果想查询学生表中所有的姓名,可以使用以下语句:

select name from student;

查询结果如下:

| name |
|------|
| 张三 |
| 李四 |
| 王五 |
| 赵六 |
| 张三 |

可以看到,查询结果中有两条重复的记录,即张三。

2、如果想去除重复记录,只显示不同的姓名,可以使用distinct关键字:

select distinct name from student;

查询结果如下:

| name |
|------|
| 张三 |
| 李四 |
| 王五 |
| 赵六 |

可以看到,查询结果中只有不同的姓名,重复的张三被去除了。

3、如果想查询学生表中有多少个不同的姓名,可以使用count函数和distinct关键字:

select count(distinct name) from student;

查询结果如下:

| count(distinct name) |
|----------------------|
| 4 |

可以看到,学生表中有4个不同的姓名。

4、distinct关键字还可以用在多个列上,表示查询结果中这些列的组合不能重复。例如,如果想查询学生表中不同的姓名和性别组合,可以使用以下语句:

select distinct name, gender from student;

查询结果如下:

| name | gender |
|------|--------|
| 张三 | 男 |
| 李四 | 女 |
| 王五 | 男 |
| 赵六 | 女 |

可以看到,查询结果中只有不同的姓名和性别组合,重复的张三和男被去除了。

以上就是sql数据库distinct去重的一些简单的示例,希望大家能够举一反三使用好这个SQL技巧。

相关文章