SQL Server - 查询最近的日期范围

pda*_*e01 5 t-sql sql-server

如果我有这样的表结构:

ProductCode  Date
Foo          4/1/2012
Foo          4/2/2012
Foo          4/3/2012
Foo          4/6/2012
Foo          4/7/2012
Foo          4/8/2012
Foo          4/9/2012
Foo          4/10/2012
Foo          4/15/2012
Foo          4/16/2012
Foo          4/17/2012
Run Code Online (Sandbox Code Playgroud)

有没有办法查询给定的日期范围ProductCodeDate(假设范围必须是连续的)?换句话说,对于该表中,富存在于3个日期范围:4/1-4/3; 4/6-4/10; 并且4/15-4/17我正在寻找给定日期的日期范围.

请注意,Foo没有日期的4/4,4/5,4/11,4/12,4/134/14.

示例:
ProductCode=Foo, Date=4/2将返回,4/1-4/3因为条目是顺序的.
ProductCode=Foo, Date=4/4将返回任何
ProductCode=Foo, Date=4/7不会返回,4/6-4/10因为条目是顺序的.
ProductCode=Foo, Date=4/12将返回什么
等等.

GSe*_*erg 0

可以用递归 CTE 来做。

declare @target_date datetime = convert(datetime, '04/07/2012', 101);

with source_table as (
  select ProductCode, convert(datetime, Date, 101) as Date
  from (
    values
    ('Foo', '4/1/2012')
   ,('Foo', '4/2/2012')
   ,('Foo', '4/3/2012')
   ,('Foo', '4/6/2012')
   ,('Foo', '4/7/2012')
   ,('Foo', '4/8/2012')
   ,('Foo', '4/9/2012')
   ,('Foo', '4/10/2012')
   ,('Foo', '4/15/2012')
   ,('Foo', '4/16/2012')
   ,('Foo', '4/17/2012')
  ) foo(ProductCode, Date)
),
recursive_date_lower as (
  select Date from source_table where Date = @target_date

  union all

  select dateadd(d, -1, r.Date) from recursive_date_lower r where exists (select 0 from source_table s where s.Date = dateadd(d, -1, r.Date))
),
recursive_date_upper as (
  select Date from source_table where Date = @target_date

  union all

  select dateadd(d, 1, r.Date) from recursive_date_upper r where exists (select 0 from source_table s where s.Date = dateadd(d, 1, r.Date))
)
select
   (select min(Date) from recursive_date_lower) as start,
   (select max(Date) from recursive_date_upper) as finish
Run Code Online (Sandbox Code Playgroud)