我有一张这样的桌子。
桌子 :
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
子句过滤掉。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句