2015-11-03 44 views
0

我需要找到過去9個月沒有銷售的所有產品代碼,因此我可以刪除它們。找到9個月或更長時間沒有銷售的產品

這是我到目前爲止有:

SELECT PI.ID as 'Product ID', ItemDescription, SOD.ID as 'Sales ID', so.despatchdate 
    FROM ProductItem as PI LEFT OUTER JOIN saleorderdetail as SOD 
    ON PI.ID = SOD.productitemid 
inner join saleorder as SO 
on SO.id = sod.saleorderid 
    where SO.despatchdate <= (getdate() - 273); 

結果是不正確的。

+0

使用則DateDiff()與'month'作爲第一個參數。 –

回答

0

使用not exists

select * from ProductItem pi 
where not exists(select * from saleorderdetail sod 
       inner join saleorder so so.id = sod.saleorderid 
       where pi.ID = sod.productitemid and so.despatchdate >= (getdate() - 273)) 

下面會更正確:

select * from ProductItem pi 
where not exists(select * from saleorderdetail sod 
       inner join saleorder so so.id = sod.saleorderid 
       where pi.ID = sod.productitemid and dateadd(m, -9, getdate())) 
0
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 
相關問題