日期:2014-05-17  浏览次数:20488 次

查询一个表内不重复的而且是最后日期的
有一个表Recharge,是充值话费的记录表。
这里面有很多手机号码。phone  然后充值记录,有个时间字段yxiaqi,
现在要查询。有效期大于今天的
select * from Recharge where yxiaqi>getdate()
是这么查,但是发现。有存在重复的手机号码。我现在想去掉重复的,只要最后时间最长的那个。应该怎么写?
比如手机号码130000000,有2个有效期,2013-12-22和2013-12-24,那么我不要22日的只要24日的。

------解决方案--------------------
select *
from Recharge   a
where exists (select 1 from (select phone,max(yxiaqi)yxiaqi from Recharge  where yxiaqi>getdate() group by phone) b where a.phone=b.phone and a.yxiaqi =b.yxiaqi )
------解决方案--------------------
select *
from 
(
select *,
   max(yxiaqi) over(partition by phone) as max_yxiaqi
from Recharge   a
where  yxiaqi>getdate()
)t
where yxiaqi = max_yxiaqi