我有一张这样的 table 。
table :
ID EnrollDate ExitDate
1 4/1/16 8/30/16
2 1/1/16 null
2 1/1/16 7/3/16
3 2/1/16 8/1/16
3 2/1/16 9/1/16
4 1/1/16 12/12/16
4 1/1/16 12/12/16
4 1/1/16 12/12/16
4 1/1/16 null
5 5/1/16 11/12/16
5 5/1/16 11/12/16
5 5/1/16 11/12/16
需要选择具有这些条件的最新记录。
所以上表的预期结果应该是:
ID EnrollDate ExitDate
1 4/1/16 8/30/16
2 1/1/16 null
3 2/1/16 9/1/16
4 1/1/16 null
我用 group by 写了查询。我不确定如何选择条件 2 和 3。
select t1.* from table t1
INNER JOIN(SELECT Id,MAX(EnrollDate) maxentrydate
FROM table
GROUP BY Id)t2 ON EnrollDate = t2.maxentrydate and t1.Id=t2.Id
请让我知道执行此操作的最佳方法是什么。
最佳答案
使用 rank()
窗口函数,我认为是可能的。
这是未经测试的,但它应该可以工作:
select t.ID, t.EnrollDate, t.ExitDate
from (select t.*,
rank() over(
partition by ID
order by EnrollDate desc,
case when ExitDate is null then 1 else 2 end,
ExitDate desc) as rnk
from tbl t) t
where t.rnk = 1
group by t.ID, t.EnrollDate, t.ExitDate
having count(*) = 1
基本思想是
rank()
窗口函数将对值为 1
的最近“最近”的行进行排名,我们在外部查询的 where
中对其进行过滤条款。如果多于一行具有相同的“最新”数据,它们将共享相同的排名
1
,但会被 having count(*) = 1
过滤掉条款。
关于sql-server - SQL Server - 选择有条件的最新记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37581969/