寻找没有为某些服务收费的订单

时间:2018-02-28 19:25:52

标签: sql where-clause

我试图查询我们的数据库,找到所有提供某些服务的工作,但是订单中的产品没有收费。我尝试过多种方式,但我无法弄明白。任何帮助,将不胜感激。这基本上就是我所寻找的:

declare @startDate datetime = '1/01/2018';
declare @endDate datetime = '2/28/2018';

select o.orderid
from orders as o
left join orderitem as oi on oi.OrderID = o.OrderID
left join job as j on j.JobID = o.JobID
left join jobservice as js on js.JobID = j.JobID
where oi.ProductID not in ('55', '65', '78')
and js.ServiceID in ('13', '16')
and o.ShippedToClientID = j.ClientID
and j.JobDate between @startDate and @endDate + 1
and o.IsVoided = '0'
group by o.orderid

1 个答案:

答案 0 :(得分:0)

我会使用not exists。像这样:

select o.orderid
from orders o
where not exists (select 1
                  from orderitem oi join 
                       job j
                       on j.JobID = o.JobID join
                       jobservice js
                       on js.JobID = j.JobID
                   where oi.OrderID = o.OrderID and
                         o.ShippedToClientID = j.ClientID and
                         oi.ProductID not in (55, 65, 78) and
                         js.ServiceID in (13, 16) and
                         j.JobDate between @startDate and @endDate + 1 and
                         o.IsVoided = 0
                  );