sql中三种去重的方式-SQL
三种 SQL 去重方法
在 SQL 中,去重是指从数据集中移除重复记录。有三种主要的方法可以实现去重:
1. DISTINCT 关键字
用途:从查询结果中移除重复的行,不区分大小写。
语法:
SELECT DISTINCT column_name1, column_name2, ... FROM table_name;
登录后复制
示例:
SELECT DISTINCT name, age FROM students;
登录后复制
2. GROUP BY 子句
用途:根据指定的列对数据进行分组,并仅返回每个组中的唯一记录。
语法:
SELECT column_name1, column_name2, ... FROM table_name GROUP BY column_name1, column_name2, ...;
登录后复制
示例:
SELECT name, MIN(age) AS min_age FROM students GROUP BY name;
登录后复制
3. HAVING 子句
用途:与 GROUP BY 结合使用,用于过滤分组后的数据,仅保留满足特定条件的记录。
语法:
SELECT column_name1, column_name2, ... FROM table_name GROUP BY column_name1, column_name2, ... HAVING condition;
登录后复制
示例:
SELECT name, COUNT(*) AS num_students FROM students GROUP BY name HAVING COUNT(*) > 1;
登录后复制