给定 SQL Server 2012 中的值列表:
Status Date
------ -----------
1 2016-12-01
1 2016-11-02
1 2016-10-20 <-- THIS
2 2016-10-01
1 2016-09-21 <-- (*)
3 2016-08-15
(*) 不需要这个,因为序列之间有一个“状态 2”行
我需要获取列表的最新日期,但是如果首先有一组相同状态的,我需要返回它们的最小日期。最好的方法是什么?
最佳答案
一种方法根本不使用窗口函数:
select top 1 t.*
from t cross join
(select top 1 t2.id from t t2 order by t2.date desc) tt
where t.date > ifnull((select max(t2.date) from t t2 where t2.id <> tt.id), '2000-01-01')
order by t.date;
子查询tt
返回表中最新行的id
。 where
子句中的子查询为任何其他 id 选择表中的最大日期。然后 where
中的比较会选择所有最新记录。
对于窗口函数,lag()
可能是最简单的:
select top 1 t.*
from (select t.*, lag(status) over (order by date) as prev_status
from t
) t
where prev_status <> status or prev_status is null
order by date desc;
where
子句获取状态发生变化的行。 top 1
和 order by date
获取最近发生此情况的时间。
关于sql - 查找行组中的最新日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42096130/