您的位置:首页 > 其它

过滤重复记录

2008-08-20 23:30 127 查看
create table tb(学校 varchar(10),年级 int,班级 varchar(10),姓名 varchar(10),性别 varchar(10),年龄 int)
insert into tb values('1中', 1, '2班', '张', '男', 20)
insert into tb values('2中', 3, '1班', '马', '男', 17)
insert into tb values('1中', 2, '2班', '李', '女', 16)
insert into tb values('2中', 3, '5班', '张', '男', 15)
insert into tb values('2中', 3, '6班', '李', '女', 18)
go

--方法1:
select a.* from tb a where 年龄 = (select min(年龄) from tb where 姓名 = a.姓名 and 性别 = a.性别) order by a.学校
--方法2:
select a.* from tb a where not exists(select 1 from tb where 姓名 = a.姓名 and 性别 = a.性别 and 年龄 < a.年龄) order by a.学校
--方法3:
select a.* from tb a,(select 姓名,性别,min(年龄) 年龄 from tb group by 姓名,性别) b where a.姓名 = b.姓名 and a.性别 = b.性别 and a.年龄 = b.年龄 order by a.学校
--方法4:
select a.* from tb a inner join (select 姓名,性别 , min(年龄) 年龄 from tb group by 姓名,性别) b on a.姓名 = b.姓名 and a.性别 = b.性别 and a.年龄 = b.年龄 order by a.学校
--方法5
select a.* from tb a where 1 > (select count(*) from tb where 姓名 = a.姓名 and 性别 = a.性别 and 年龄 < a.年龄) order by a.学校

drop table tb

/*
学校 年级 班级 姓名 性别 年龄
---------- ----------- ---------- ---------- ---------- -----------
1中 2 2班 李 女 16
2中 3 1班 马 男 17
2中 3 5班 张 男 15

(所影响的行数为 3 行)

学校 年级 班级 姓名 性别 年龄
---------- ----------- ---------- ---------- ---------- -----------
1中 2 2班 李 女 16
2中 3 1班 马 男 17
2中 3 5班 张 男 15

(所影响的行数为 3 行)

学校 年级 班级 姓名 性别 年龄
---------- ----------- ---------- ---------- ---------- -----------
1中 2 2班 李 女 16
2中 3 1班 马 男 17
2中 3 5班 张 男 15

(所影响的行数为 3 行)

学校 年级 班级 姓名 性别 年龄
---------- ----------- ---------- ---------- ---------- -----------
1中 2 2班 李 女 16
2中 3 1班 马 男 17
2中 3 5班 张 男 15

(所影响的行数为 3 行)

学校 年级 班级 姓名 性别 年龄
---------- ----------- ---------- ---------- ---------- -----------
1中 2 2班 李 女 16
2中 3 1班 马 男 17
2中 3 5班 张 男 15

(所影响的行数为 3 行)

*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: