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 

,並會導致下面的輸出,如果ischange沒有改變那麼它將從查詢中獲取硬編碼的結束日期,否則它將抓取最少的ischange值更改日期

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

但我在尋找這樣設置

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

回答

1

結果你想要的時間,其中ischanged爲0,可以做到這一點使用的row_number()差異:

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; 
+0

感謝您的快速反應。但不知道如何在我的查詢中使用你的解決方案 – 2014-10-29 01:32:09

+0

謝謝你的幫助! – 2014-10-29 01:43:31