2014-04-23 4 views
0
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) 

위 쿼리는 프로세스에서 코일 목록과 시작 날짜와 종료 날짜를 반환합니다. 나는 코일의 끝 날짜와 다음 코일의 시작 날짜 사이의 차이점을 찾아서 다른 코일을 프로세스에로드하는 데 얼마나 많은 시간이 소비되는지 확인하는 방법을 찾고있다. 예를 들어 행 1의 종료일은 2013-01-01 07 : 00 : 00.000이고 행 2의 시작일은 2013-01-01 07 : 01 : 00.000입니다. 해당 특정 행에서 찾고자하는 결과 집합은 1입니다.SQL 문에서 두 행의 차이를 얻는 방법

테이블 자체에 조인하고 행에 추가 할 필요가 있지만 구문과 논리적 사고 프로세스가 필요하다는 것을 알고 있습니다. 어떤 도움을 주셔서 감사합니다!

+0

MySQL과 SQL 서버가 제대로 태그를 다른 짐승 :

는 여기에 함께 넣어 간단한 예입니다. – Mihai

+0

사용중인 RDBMS를 파악한 후에는 원하는 DDL (및/또는 sqlfiddle)과 함께 원하는 결과 집합을 제공하는 것이 좋습니다 – Strawberry

+1

그리고 SQL Server 인 경우 버전은 무엇입니까? – McCee

답변

0

좋은 소식은 당신이 LEAD()LAG()을 소개 한 SQL Server 2012에 있다는 것입니다. 작업이 매우 쉽습니다. LEAD()은 현재 행을 가져 와서 다음 행과 비교합니다. LAG()은 그 반대입니다.

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

상황에 맞게 더 작게 편집하십시오. – McCee

+0

우수함, 정확히 내가 필요로하는 것. 고마워. 존재하지 않았다. –

관련 문제