过滤重复记录

来源:互联网 发布:nginx last break 编辑:程序博客网 时间:2024/06/05 10:32
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 行)

*/