码迷,mamicode.com
首页 > 数据库 > 详细

Sqlserver取最近一分组中最新一条记录

时间:2015-07-16 11:02:27      阅读:174      评论:0      收藏:0      [点我收藏+]

标签:

/* 1 用子查询 可以过滤掉parentID为NULL的*/
select * from Bid_ProjectPackageAlteredDesignInfo t0
where exists
(
    select 1 from
    (
        select ParentID, max(AlterTime) as AlterTime
        from Bid_ProjectPackageAlteredDesignInfo 
        group by ParentID
    ) x
    where x.ParentID = t0.ParentID and x.AlterTime = t0.AlterTime
)
select a.*
 from Bid_ProjectPackageAlteredDesignInfo a
 inner join
 (select ParentID,
         max(AlterTime) AlterTime
  from Bid_ProjectPackageAlteredDesignInfo 
  group by ParentID) b on a.ParentID=b.ParentID and a.AlterTime=b.AlterTime
 /*不可以过滤掉parentID为NULL的*/
select a.* 
 from Bid_ProjectPackageAlteredDesignInfo a 
 where not exists
 (
    select 1 from Bid_ProjectPackageAlteredDesignInfo b where b.ParentID=a.ParentID and b.AlterTime>a.AlterTime
  )



/* 2 用窗口函数 *//*不可以过滤掉parentID为NULL的*/
select * from
(
select ParentID,AlterTime
, max(AlterTime) over(partition by ParentID) as AlterTimeMax
from Bid_ProjectPackageAlteredDesignInfo
) x
where AlterTimeMax =AlterTime

 

Sqlserver取最近一分组中最新一条记录

标签:

原文地址:http://www.cnblogs.com/yongtaiyu/p/4650322.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!