2012-12-05 42 views
1

的不同列的SQL查詢我有不同的記錄的列開始日期和結束日期。 如果我按開始日期的升序對記錄進行排序。 ,並希望連續查找一行的開始日期和前一行的結束日期之間的差異。用於獲取差異高炮不同行

e.g. 
Table: Data 
------------ 
Date1   Date2   
13-DEC-2011  15-DEC-2011  
18-DEC-2011  16-DEC-2011  
21-DEC-2011  24-DEC-2011 

多了一個查詢,如果我有一個第三列 說ID,我想區別通過分組這些ID的 如

   ID   Date1    Date2   
       1  13-DEC-2011  15-DEC-2011  
       1  18-DEC-2011  16-DEC-2011  
       2  21-DEC-2011  24-DEC-2011 
       2  25-JAN-2012  25-FEB-2012 
       2  29-FEB-2012  25-MAR-2012 


       and I need : 


      ID INTERVAL FREE 
       1 15 DEC to 18 DEC 
       2 24dec to 25 jan;25 feb to 29 feb 
+0

看看這個答案我的。可能有幫助。 http://stackoverflow.com/questions/11262260/finding-free-blocks-of-time-in-mysql-and-php –

回答

3

這裏是SQLFiddle demo

with t1 as 
(
select t.*, 
     row_number() over (order by date1) rn 
     from t 
) 
select t1.date1 as d1,t1.Date2 as d2 , 
t2.Date2 as PreviousDate2, 
t1.Date1-t2.Date2 as DIff 
from t1 
left join t1 t2 on t1.rn=t2.rn+1 
order by t1.rn 

下面是一個查詢回答你編輯的問題:

SQLFiddle DEMO

如果您需要爲一個逗號分隔的行收集每個ID的行,您應該在客戶端而不是SQL中執行。

with t1 as 
(
select t.*, 
     row_number() over (partition by id order by date1) rn 
     from t 
) 
select t1.id, 
t2.Date2 as PreviousDate2, 
t1.date1 as d1 
from t1 
left join t1 t2 on (t1.rn=t2.rn+1) and (t1.id=t2.id) 
where t2.Date2 is not null 
order by t1.id,t1.rn 
+0

thnaks一個lot..now一個更query..what如果我有一羣這些.. – Richa

+0

請參閱編輯queestion – Richa

+0

我添加了一個查詢你的問題的第二部分 – valex

0

試試這個::

SELECT 
DATEDIFF(temp1.from, temp2.to) as diff 
from 
(
SELECT t.DATE1 as from, 
     @rownum := @rownum + 1 AS rank1 
    FROM YOUR_TABLE t, 
     (SELECT @rownum := 0) r 
order by Date1 
) as temp1 
inner join 

(
SELECT t.DATE2 as to, 
     @rownum := @rownum + 1 AS rank2 
    FROM YOUR_TABLE t, 
     (SELECT @rownum := 1) r 
order by Date1 
) as temp2 on (temp1.rank1=temp2.rank2)