sql查询过滤重复语句

loveu0508 2010-11-09 05:06:05
表test 数据如下:
id num date
1 35 2010-9-10
1 36 2010-9-11
1 34 2010-9-12
2 35 2010-9-10
2 34 2010-9-11
3 34 2010-9-12
3 35 2010-9-11
3 36 2010-9-10

查询结果如下:
id num date
1 34 2010-9-12
2 34 2010-9-11
3 34 2010-9-12

要求:按id去掉重复记录,按date排序 取date最大的那一条

请大侠们指教
...全文
72 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
duanzhi1984 2010-11-09
  • 打赏
  • 举报
回复
create table #(id int,num int,date varchar(10))
insert into #

select 1 ,35, '2010-9-10'union all
select 1 ,36, '2010-9-11'union all
select 1 ,34 ,'2010-9-12'union all
select 2 ,35 ,'2010-9-10'union all
select 2 ,34 ,'2010-9-11'union all
select 3 ,34 ,'2010-9-12'union all
select 3 ,35 ,'2010-9-11'union all
select 3 ,36 ,'2010-9-10'

select id, num ,date from # a where not exists (select 1 from # b where a.id=b.id And a.date<b.date )


1 34 2010-9-12
2 34 2010-9-11
3 34 2010-9-12
loveu0508 2010-11-09
  • 打赏
  • 举报
回复
首先过滤掉id重复的记录 即id重复的只保留一条

那么保留那一条呢?就是日期最大的那条

就这样

怎么写呢????
jwdream2008 2010-11-09
  • 打赏
  • 举报
回复
select id, num ,date from TB a where not exists (select 1 from TB where a.id=id And a.date<date )

22,206

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧