SQL Server:查找公司/部门ID的最新生效日期

时间:2018-06-26 18:59:25

标签: sql sql-server sql-server-2008

我们有一个DeptID表,每个公司/ deptID /操作都有多个记录。无论采取什么措施,如何提取仅包含公司/ deptID的最新生效日期的列表?我想在查询记录中显示这些列和其他一些列。

 Co#   DeptID  Action  Eff Date
 ---   ------  ------  --------
 01    12      Closed  03/22/2018 
 01    24      Closed  03/03/2014 
 01    24      Open    07/01/2010
 01    365     Closed  01/01/2008
 01    365     Open    05/01/2010

此SQL已关闭,但是我无法让它仅列出该操作的最后生效日期。如果我删除该操作,则它将列出公司/ deptID的最后生效日期,但是我需要知道该操作适用于哪个操作-打开还是关闭?

select distinct 
    loc.CompanyNumber, loc.DeptID, loc.Action, 
    max(loc.effdate) over (partition by companynumber, deptid) as LocmaxDate
from 
    [dbo].[LocationsOpenClosed] as loc

2 个答案:

答案 0 :(得分:2)

您可以使用subquery

select loc.*
from [dbo].[LocationsOpenClosed] as loc
where effdate = (select max(loc1.effdate) 
                 from [dbo].[LocationsOpenClosed] as loc1
                 where loc1.companynumber = loc.companynumber 
                       loc1.deptid = loc.deptid
                 );

但是,我也建议使用排名功能:

select *
from (select *, 
             row_number() over (partition by companynumber, deptid order by effdate desc) as seq
      from [dbo].[LocationsOpenClosed]
     ) loc
where seq = 1;

答案 1 :(得分:0)

您可以将CTE(公用表表达式)与Rownumber()结合使用,如下所示:

.ONESHELL