首页 > 解决方案 > SQL查询在表中获得一个“行”

问题描述

我需要从 SQL 中的表中获取结果列表,以便我需要日期值紧接在 where 语句选择的行之前的行。在下图中,我会写:

select * from Table t where Color = 'blue'

但我不知道如何获得突出显示的蓝色行上方的行。示例是 Excel,但只是为了便于生成示例。现实生活中的“蓝色”是更多的连接和数据,但对于一个最低限度的完整示例,这是可行的。假设日期并不总是按日期时间排序,但我总是希望该条目紧挨在“蓝色”条目之前,日期时间明智。

在此处输入图像描述

标签: sql-server

解决方案


如果没有重复的日期,则使用 UNION ALL:

select * from Table where Color = 'blue'
union all
select * from Table t 
where 
  t.Color is null 
  and
  (
    select color from Table where date = (
      select min(date) from Table where date > t.date)
  ) = 'blue'
order by date

推荐阅读