简体   繁体   中英

How to get the difference between two rows in a sql statement

select distinct 
    shipperinf_coilid, max(PilerInf_CreateDate), max(ShipperInf_CreateDate)
from 
    tblL3SendProductionData
where 
    ShipperInf_CoilId not in (select distinct shipperinf_coilid 
                              from table_2 
                              where orderinf_ordernumber like 'b%') 
    and pilerinf_createdate != '1900-01-01 00:00:00.000'
group by  
    shipperinf_coilid
order by 
    max(PilerInf_CreateDate)

The above query returns a list of coils and their start date and end date in a process. I'm trying to find a way to find the difference between the end date of a coil and the start date of the next coil to see how much time is spent loading another coil into the process. So for example row 1's end date could say 2013-01-01 07:00:00.000 and row 2's start date is 2013-01-01 07:01:00.000. the result set I would be looking for in that specific row is 1.

I know I need to do something with joining the table on itself and adding to the row, but the syntax and logical thought process needed is alluding me. Thanks for any help!

The great news is that you're on SQL Server 2012, which introduced LEAD() and LAG() - making your task very easy. LEAD() takes the current row and compares it to the next. LAG() does the opposite.

Here's a quick example I put together:

create table #results (id int, startDate datetime, endDate datetime)

insert into #results
select  1, cast('10/1/2012' as datetime), cast('12/1/2012' as datetime)
insert into #results
select  1, cast('12/15/2012' as datetime), cast('12/31/2012' as datetime)
insert into #results
select  1, cast('2/1/2013' as datetime), cast('12/1/2013' as datetime)

select  id, startDate, endDate,
        DATEDIFF(day, endDate, LEAD(startDate) OVER (ORDER BY id)) DaysUntilNextCoil,
        DATEDIFF(day, startDate, LAG(endDate) OVER (ORDER BY id)) DaysSincePreviousCoil
from #results

drop table #results

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM