Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/sql-server/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 基于位值的多个日期范围_Sql_Sql Server_Sql Server 2008_Common Table Expression_Recursive Query - Fatal编程技术网

Sql 基于位值的多个日期范围

Sql 基于位值的多个日期范围,sql,sql-server,sql-server-2008,common-table-expression,recursive-query,Sql,Sql Server,Sql Server 2008,Common Table Expression,Recursive Query,我有下表的数据 id departmentid ischanged date 3 22 0 2014-01-04 3 101 0 2014-01-05 3 125 1 2014-01-06 3 169 1 2014-01-07 3 175 0 2014-01-08 3 176 0

我有下表的数据

id departmentid  ischanged date
3   22             0      2014-01-04
3   101            0      2014-01-05
3   125            1      2014-01-06
3   169            1      2014-01-07
3   175            0      2014-01-08
3   176            0      2014-01-09
3   177            0      2014-01-10

5   22             0      2014-01-04
5   101            0      2014-01-05
5   125            0      2014-01-06
5   169            0      2014-01-07
5   175            0      2014-01-08
5   176            0      2014-01-09
5   177            0      2014-01-10
我现在的问题是

insert into #temp1(id, startdate, enddate)
SELECT t1.id, '2014-1-4' as startdate, min(isnull(enddate,'2014-01-10')) as endDate
FROM (
            SELECT id, departmentid, ischanged
            FROM dbo.[table]    where date = '2014-1-4'
      ) AS t1
        left join 
        (
            SELECT id, departmentid, ischange , date
            FROM dbo.[table]    where date >= '2014-1-4'
        ) as t2
         on t1.id = t2.id and (t1.ischange <> t2.ischange)
group by t1.id
但我正在寻找这样的结果集

id  startdate      enddate
3   2014-01-04    2014-01-05
3   2014-01-08    2014-01-10
5   2014-01-04    2014-01-10

您需要
ischanged
为0的句点。您可以使用
行数()的差异来执行此操作。


谢谢你的快速回复。但我不知道如何在我的查询中使用您的解决方案
id  startdate      enddate
3   2014-01-04    2014-01-05
3   2014-01-08    2014-01-10
5   2014-01-04    2014-01-10
select id, min(date) as startdate, max(date) as enddate
from (select t.*,
             (row_number() over (partition by id order by date) -
              row_number() over (partition by id, ischanged order by date)
             ) as grp
      from table t
     ) t
where ischanged = 0
group by id, grp;