您的位置:首页 > 数据库

sql分组取最大一条

2017-08-28 11:44 302 查看
declare @Tab table
(Num int, Name varchar(2),   Time DATETIME)
insert into @tab select 1    ,'a',        '2009/05/01'
insert into @tab select 1    ,'a',        '2009/05/02'
insert into @tab select 1    ,'a',        '2009/05/03'
insert into @tab select 2    ,'b',        '2009/05/04'
insert into @tab select 2    ,'b',        '2009/05/05'
insert into @tab select 3    ,'c',        '2009/05/06'
insert into @tab select 3    ,'c',        '2009/05/07'
insert into @tab select 5    ,'e',        '2009/05/08'
insert into @tab select 1    ,'a',        '2009/05/09'
insert into @tab select 1    ,'a',        '2009/05/10'
select  * from @Tab t where  not exists(select 1 from @Tab where num=t.num and [time]<t.[time])
/*
Num         Name Time
----------- ---- -----------------------
1           a    2009-05-01 00:00:00.000
2           b    2009-05-04 00:00:00.000
3           c    2009-05-06 00:00:00.000
5           e    2009-05-08 00:00:00.000
(4 行受影响)
*/


  select * from test where b in (select max(id) from test group by a)
  适用于所有数据库:
  
  select t1.a,t1.b,t1.c
  from test t1
  inner join
  (seelct a,max(b) as b from test group by a) t2
  on t1.a=t2.a and t1.b=t2.b
  
  适用于所有数据库:
  
  select a,b,c
  from(
  select a,b,c
  ,row_number()over(partition by a order by b desc) rn
  from test
  )
  where rn=1
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: