我正在尝试在表格中查找过去几周没有活动的记录(工作单)。
我需要从日期字段不在的表格中选择不同的工单从当前日期算起的过去两周。
如果日期早于过去两周,我可以获得工作订单。
select distinct WorkOrder
from SMWorkOrder
where SMCo = 1 and WorkOrder in
(select WorkOrder
from SMWorkCompleted
where SMCo = 1 and Date < DATEADD(WEEK, -2, GETDATE()))
如何获得此表格中的行的日期超过过去两周且在过去两周内没有任何行的工作单?
答案 0 :(得分:1)
使用左外连接在以下情况下非常有效:
SELECT
o.WorkOrder
FROM
SMWorkOrder o
LEFT JOIN SMWorkCompleted c
ON o.WorkOrder = c.WorkOrder
AND c.Date >= DATEADD(WEEK,-2,CAST(GETDATE() AS DATE)) AND c.Date <= GETDATE()
AND c.SMCo = 1
WHERE
c.WorkOrder is NULL
AND o.SMCo = 1
但是请注意,我怀疑你们两张桌子上都有SMCo,但是你应该把它从where条件中删除,如果不是在SWorkOder表上,和/或如果在SWorkCompleted表上那么将它从连接的ON条件中删除
对于IN方法,您实际上想要使用NOT IN:
SELECT
o.WorkOrder
FROM
SWorkOrder o
WHERE
o.SMCo = 1
AND o.WorkOrder NOT IN (
SELECT
WorkOrder
FROM
SMWorkCompleted c
WHERE
c.Date >= DATEADD(WEEK,-2,CAST(GETDATE() AS DATE)) AND c.Date <= GETDATE()
AND c.SMCo = 1
)
注意如果WorkOrder可能为NULL,请不要使用!
NOT EXISTS方法也很有效:
SELECT
o.WorkOrder
FROM
SWorkOrder o
WHERE
o.SMCo = 1
AND NOT EXISTS (
SELECT
WorkOrder
FROM
SMWorkCompleted c
WHERE
c.WorkOrder = o.WorkOrder
AND c.Date >= DATEADD(WEEK,-2,CAST(GETDATE() AS DATE)) AND c.Date <= GETDATE()
AND c.SMCo = 1
)
答案 1 :(得分:-1)
尝试使用MAX日期来分配工单...