2012-08-09 51 views
0

這是我當前的查詢:SQL如何申請DateDiff的兩個不同的where子句

select serial_number, order_number, 
(select TOP 1 PRODUCT_ID from PS_ORD_LINE PL 
where PL.ORDER_NO = WO.order_number 
and CAT_DESCR = 'SYSTEM' and ORD_LINE_STATUS = 'O' 
ORDER BY ORDER_INT_LINE_NO) as model, 
(select datediff(minute, min(complete_time), min(start_time)) 
from TRACKED_OBJECT_HISTORY TOH1 
where TOH1.op_name IN ('Assembly', 'Pre-Final') 
and TOH1.tobj_key = TOH.tobj_key) as waiting_time1, 
from UNIT U 
left join WORK_ORDER WO on U.order_key = WO.order_key 
left join TRACKED_OBJECT_HISTORY TOH on TOH.tobj_key = U.unit_key 
where WO.creation_time > '5/1/12' and WO.creation_time < '7/31/12' 
group by serial_number, order_number, tobj_key 

DateDiff中間的部分是我的問題。

所以AssemblyPre-Final是單位掃描兩個不同的站的名稱。Assembly通常是第一線,通過Pre-Final緊接着。

我想要做的是計算單位掃描出Assembly之後和該單位掃描到Pre-Final之後的經過時間。 complete_time馬克當一個單位被掃描出站,並start_time是當它在掃描真實。

現在,我的查詢不起作用,因爲這兩個start_timecomplete_timeAssembly,因爲它是第一站。不過,我想要complete_time來參考Assembly,而我想start_time指的是Pre-Final

我應該怎麼做呢?

+0

對不起,標題應該是datediff,而不是我的壞 – user1558927 2012-08-09 23:38:31

回答

1

也許使用

DATEDIFF(MINUTE, 
     (SELECT MIN(complete_time) 
      FROM TRACKED_OBJECT_HISTORY toh1 
      WHERE toh1.op_name = 'Pre-Final' AND toh1.tobj_key = toh.tobj_key), 
     (SELECT MIN(start_time) 
      FROM TRACKED_OBJECT_HISTORY toh2 
      WHERE toh2.op_name = 'Assembly' AND toh2.tobj_key = toh.tobj_key) 
     ) AS waiting_time1, 

0

我不完全理解你的數據庫結構,但如果你應該能夠使用子查詢拉兩次,每次項目。下面是代碼的樣子,假設tobj_key引用一個對象,並且每個對象只經過一次機器。

SELECT 
    DateDiff(n,AssemblyTime,PrefinalTime) 
FROM (
    SELECT 
     tobj_key, 
     complete_time AS 'AssemblyTime' 
    FROM TRACKED_OBJECT_HISTORY 
    WHERE op_name = 'Assembly' 
    ) AS sub1 
JOIN (
    SELECT 
     tobj_key, 
     start_time AS 'PrefinalTime' 
    FROM TRACKED_OBJECT_HISTORY 
    WHERE op_name = 'Assembly' 
    ) AS sub2 ON sub1.tobj_key = sub2.robj_key