日期:2014-05-18 浏览次数:20558 次
create table #tb(aa int,bb datetime,cc varchar(50)) insert into #tb values (65443, '2012-04-11' ,'40'), (65443, '2012-04-12' ,'50') , (65443 ,'2012-04-21' ,'250') , (65446 ,'2012-04-29' ,'130') , (65447 ,'2012-04-17' ,'test') , (65447 ,'2012-04-29' ,'1290'), (65448 ,'2012-04-29' ,'650'), (65449 ,'2012-04-28' ,'1100'), (65449 ,'2012-04-29' ,'190'); select aa,bb,cc from (select *,row_number()over(partition by aa order by bb desc) as rin from #tb)fin where fin.rin=1 drop table #tb /* (9 row(s) affected) aa bb cc ----------- ----------------------- -------------------------------------------------- 65443 2012-04-21 00:00:00.000 250 65446 2012-04-29 00:00:00.000 130 65447 2012-04-29 00:00:00.000 1290 65448 2012-04-29 00:00:00.000 650 65449 2012-04-29 00:00:00.000 190 (5 row(s) affected) */
------解决方案--------------------
create table tb(aa int,bb datetime,cc varchar(50)) insert into tb values (65443, '2012-04-11' ,'40'), (65443, '2012-04-12' ,'50') , (65443 ,'2012-04-21' ,'250') , (65446 ,'2012-04-29' ,'130') , (65447 ,'2012-04-17' ,'test') , (65447 ,'2012-04-29' ,'1290'), (65448 ,'2012-04-29' ,'650'), (65449 ,'2012-04-28' ,'1100'), (65449 ,'2012-04-29' ,'190'); select * from tb as a where not exists (select 1 from tb where aa = a.aa and bb > a.bb) drop table tb
------解决方案--------------------
select a.aa,a.bb,b.cc from ( select aa,MAX(bb) as bb from #tb group by aa) a join #tb b on a.aa=b.aa and a.bb=b.bb