declare @users table(id int , name varchar(300),sex varchar(10) , age int, addtime datetime) ;
insert into @users
select 1,'liu','男',30,GETDATE()
union select 2 , 'liu','女',30 , GETDATE()
union select 3 ,'yu','男', 29, GETDATE()
union select 4 , 'liu', '女',30, GETDATE() ;
select name,sex,age,min(addtime),min(id) as id from users
题目:
有一个表users,主键是Id,有字段name,sex,age,addtime,把name,sex,age相同记录找出来,只剩下addtime最小的记录,其他的删除掉
如上: 删除 Id 是4 的记录.
答案:
delete @users where id not in (
select id from
(
select name,sex,age,min(addtime) as ma ,min(id) as id
from @users group by name,sex,age
) as dww
)
妙处在于: 第二个聚合函数: 针对于前面的结果,只有一条: 所以用 Min , Max ,Avg 都没关系.只是找出这条记录所对应的Id来!