SQL如何将DateDiff应用于两个不同的where子句

时间:2012-08-09 23:31:35

标签: sql sql-server function datetime

这是我目前的查询:

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就是在扫描一个单位时。{/ p>

目前,我的查询无效,因为start_timecomplete_time都引用Assembly,因为它是第一站。但是,我希望complete_time引用Assembly,同时我希望start_time引用Pre-Final

我该怎么做呢?

2 个答案:

答案 0 :(得分: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,

答案 1 :(得分: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