sql - 查找行组中的最新日期

标签 sql sql-server

给定 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返回表中最新行的idwhere 子句中的子查询为任何其他 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 1order by date 获取最近发生此情况的时间。

关于sql - 查找行组中的最新日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42096130/

相关文章:

sql - PostgreSQL:如何在SQL查询中将date_trunc的星期开始日期从星期一更改为另一天?

sql - Postgres 按时间戳分组为 6 小时桶

mysql - 如何从 Lightswitch 调用 MySQL 存储过程?

sql-server - 无法在 SQL Server Management Studio 2008 SP3 中打开 .sdf 文件

SQL 服务器 2008 : What is the best way for inserting big chunk of data?

SQL 查找可能的重复项

mysql - UPDATE 语句更新一行中的多个字段

mysql - 扩展从数据库中获取数据的规模

sql-server - 10 :00 AM PST in SQL Server 的数据类型是什么

sql-server - sql server合并两个表中的值