用于获取不同行的不同列之间差异的SQL查询

时间:2012-12-05 13:15:34

标签: mysql sql-server-2008

我的列开始日期和结束日期有不同的记录。 如果我按开始日期的升序排序记录。 并希望连续找到上一行的开始日期和上一行的结束日期之间的差异。

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分组 e.g

              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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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)