2014-09-10 94 views
1

我必須計算容器退出設施的日子,每次容器到達時它都有不同的主鍵但ID相同。相同的集裝箱可以多次出發和抵達,但我當然必須計算最近出發和到達之間的日期。我一直在嘗試這樣做,使用RANK()函數以上通過計算出發地和目的地:通過Rank鏈接的SQL()超過

SELECT DISTINCT *, datediff(day,c_out.time_out, c_in.time_In) as Days 
FROM 

(SELECT Container_ID 
, time_out 
, RANK() OVER (PARTITION by Container_ID, order by time_out) as leave_no 
FROM Containers 
WHERE Departure_type='TRUCK'    --EDIT2 ************************************ 
) c_out INNER JOIN 
(SELECT container_ID as Incoming_ID 
, time_in 
,RANK() OVER (PARTITION by Container_ID, order by time_in) as arrive_no 
FROM Containers) c_in 
ON c_out.container_id=c_in.incoming_id 

WHERE c_out.leave_no=c_in.arrive_no+1 

這裏的想法是樹葉匹配項:如果容器左側爲n個時,接下來的到來將是n + 1

但作爲一個結果,我收到類似

CONTAINER_ID TIME_OUT LEAVE_NO INCOMING_ID TIME_IN ARRIVE_NO DAYS 
ABC123   2014-04-11  2  ABC123  2013-11-21 1   -141 

編輯:儘管下面給出的解決方案做的工作,我還是想知道如何加入的RANK()

EDIT2:讓我澄清一下:容器具有特別的方式(一些可能一個)

回答

1

你可以嘗試更多的東西蠻力,要離開有點像:

SELECT Container_ID 
, time_out 
, (select min(c2.time_in) 
     from Containers c2 
     where c2.container_ID = c1.container_ID 
     and c2.time_in > c1.time_out) as returned 
FROM Containers c1 
+0

我會告訴你,當服務器將完成它的工作... 10分鐘,仍然處理。蠻力是蠻橫的。 – Yasskier 2014-09-10 23:56:43

+0

完成了嗎? ;-) – Chrisky 2014-09-16 06:07:04

+1

正確索引表後,它變得非常快:) – Yasskier 2014-09-16 07:09:08

0

嘗試所有可能做的排名計算一次:

with cte as (
    SELECT Container_ID 
     , time_out 
     , time_in 
     , RANK() OVER (PARTITION by Container_ID order by time_out) as leave_no 
     , RANK() OVER (PARTITION by Container_ID order by time_in) as arrive_no 
    FROM Containers 
) 
select c_out.container_no 
    , c_out.time_out 
    , c_in.time_in, datediff(day,c_out.time_out, c_in.time_In) 
from cte as c_out 
join cte as c_in 
    on c_out.container_id = c_in.container_id 
    and c_out.leave_no = c_in.arrive_no + 1