【问题标题】:Find latest date in groups of rows在行组中查找最新日期
【发布时间】:2017-02-07 17:23:17
【问题描述】:

鉴于 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”行

我需要获取列表的最新日期,但是如果首先有一组相同的状态,我需要返回它们的最小日期。最好的方法是什么?

【问题讨论】:

标签: sql sql-server


【解决方案1】:

一种方法根本不使用窗口函数:

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 获取最近发生的时间。

【讨论】:

  • 我使用了带有 lag() 的查询,它运行良好!非常感谢!
【解决方案2】:

我会这样做:

  select
        status,
        min(date)
    from table
    where status in 
    (select
        status
    from table
    group by 1
    having count(date) > 1)
    group by 1

使用一个查询检查多次出现的所有状态,然后从这些状态中选择最短日期。

【讨论】:

  • 此查询返回所有记录的最短日期(在我的例子中,我用 (*) 标记的行)。我需要从第三行获取日期。
猜你喜欢
  • 2020-04-28
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 2017-09-04
相关资源
最近更新 更多