SQL Server 2008(无LAG功能) - 值更改时的组最小/最大日期

时间:2015-04-10 06:13:03

标签: sql-server-2008-r2 lag

我有一个现有的@table

ID  Date    Val
1   2014-10-01  1
2   2014-10-02  1
3   2014-10-03  2
4   2014-10-04  2
5   2014-10-05  2
6   2014-10-06  1
7   2014-10-07  1
8   2014-10-08  1
9   2014-10-09  1

日期序列非常重要。我需要查看每个Val序列的第一个和最后一个日期:

如何让SQL返回每个序列的最小/最大日期?我需要表明: 即。

1   2014-10-01  2014-10-02
2   2014-10-03  2014-10-05
1   2014-10-06  2014-10-09

我在其他具有2012年LAG功能的开发人员的帮助下完成了这项工作,但我需要使用2008年

尝试失败:

  select t.Val,MIN(t.date),MAX(tnext.date)
from @T t join
     @T tnext
     on t.id = tnext.id - 1 and
      t.Val <> tnext.val
      group by 
      t.val

设定:

declare @T table(ID int,[Date] date,Val int)
Insert Into @T(ID,[Date],Val)
 values
(1,'2014/10/01',    1),
(2,'2014/10/02',    1),
(3,'2014/10/03',    2),
(4,'2014/10/04',    2),
(5,'2014/10/05',    2),
(6,'2014/10/06',    1),
(7,'2014/10/07',    1),
(8,'2014/10/08',    1),
(9,'2014/10/09',    1)

1 个答案:

答案 0 :(得分:1)

我相信这个查询应该有效:

select 
    val, 
    start_date = min(date), 
    end_date   = max(date) 
from 
    (
    select 
       val, 
       date, 
       grp = row_number() over (partition by val order by date) 
           - row_number() over (order by date) 
    from 
       @t 
    ) x 
group by 
    grp, val
order by 
    min(date)

上面的查询假定日期是严格顺序的。

Sample SQL Fiddle