简体   繁体   中英

SQL how to apply DateDiff for two different where clauses

This is my current query:

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

The part in the middle with DateDiff is my problem.

So Assembly and Pre-Final are the names of two different stations that units are scanned in. Assembly is usually first in line, followed immediately by Pre-Final .

What I'm trying to do is to calculate the elapsed time after a unit scans out of Assembly and before that unit scans into Pre-Final . complete_time marks when a unit is scanned out of a station, and start_time is when it's scanned in.

Right now, my query doesn't work because both start_time and complete_time refer to Assembly because it's the first station. However, I want complete_time to refer to Assembly while I want start_time to refer to Pre-Final .

How should I go about doing this?

Perhaps using

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,

etc.

I don't completely understand your database structure, but if you should be able to use subqueries to pull the two times for each item. Here's a sample of what the code would look like, assuming that tobj_key refers to an object and each object only goes through the machines once.

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

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