declare @products table
(
Id int primary key not null
, Name nvarchar(32) not null
)
insert @products values(1, 'Has Recent Sales Order')
insert @products values(2, 'Does Not Have Recent Sales Order')
declare @sos table
(
Id int primary key not null,
DespatchDate datetime not null
)
insert @sos values (1, getdate())
insert @sos values (2, DATEADD(month, -10, getdate()))
declare @sods table
(
ProductId int not null,
SaleOrderId int not null
)
insert @sods values(1, 1)
insert @sods values(2, 2)
-- select only those products that do not have a recent sales order
SELECT
PI.ID as 'Product ID'
, PI.Name -- for demonstrative purposes only
FROM
@products as PI
LEFT OUTER JOIN @sods as SOD
ON PI.ID = SOD.ProductId
left outer join @sos as SO
on SO.id = sod.saleorderid
-- retreive sales orders within past 9 months only
and DATEADD(month, -9, getdate()) <= SO.despatchdate
group by
PI.ID
, PI.Name -- for demonstrative purposes only
having
-- only sales orders in past 9 months were returned
-- so filter for no sales orders
count(so.id) = 0
使用則DateDiff()與'month'作爲第一個參數。 –