这是我目前的查询:
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
中间的部分是我的问题。
因此Assembly
和Pre-Final
是扫描单位的两个不同电台的名称。Assembly
通常排在第一位,紧接着是Pre-Final
。
我要做的是计算单位扫描Assembly
之后和该单位扫描到Pre-Final
之前的经过时间。当一个单元从一个工作站扫描出来时会complete_time
标记,而start_time
就是在扫描一个单位时。{/ p>
目前,我的查询无效,因为start_time
和complete_time
都引用Assembly
,因为它是第一站。但是,我希望complete_time
引用Assembly
,同时我希望start_time
引用Pre-Final
。
我该怎么做呢?
答案 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