2017-02-17 91 views
0

我想创建一个视图,我想要查看过去6个月内未售出的物品清单。我尝试了几种方法,但没有一种工作正确。 请指导我。 我有一个销售数据集市有一个表的项目号,我从另一个表中获取项目号,这是所有项目列表的项目表。 这里有两种方法: 我不能制作临时表,因为这是一个视图?最近6个月内没有售出物品的sql视图

select distinct a.ItemID, a.TranDate Into #Itemslast6months 
from SalesDataMart a 
where TranDate >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0) 

Select distinct m.ITMNO_0 into #ItemsNotSoldLast6Months 
from ITEMMASTER as m 
Where not exists (select ItemID 
        from #Itemslast6months as B 
        where m.ITMNO_0 = B.ItemID) 


Select n.ITMNO_0, s.[Description], max(s.TranDate) last_Transaction_Date 
from #temsNotSoldLast6Months n 
join SalesDataMart s on n.ITMNO_0 = s.ItemID 
group by n.ITMNO_0, s.[Description] 

第二个方法:


WITH ItemsSoldLast6Months (ItemID, TranDate) 
     AS 
     (
     select distinct a.ItemID, a.TranDate 
     from SalesDataMart a 
     where TranDate >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0) 

    ) 

    WITH ItemsNotSoldLast6Months (ItemNO) 
     AS 
     (
     Select distinct m.ITMNO_0 
from ITEMMASTER as m 
Where not exists (select ItemID 
        from ItemsSoldLast6Months as B 
        where m.ITMNO_0 = B.ItemID) 

    ) 


Select n.ITMNO_0, s.[Description], max(s.TranDate) last_Transaction_Date 
from #temsNotSoldLast6Months n 
join SalesDataMart s on n.ITMNO_0 = s.ItemID 
group by n.ITMNO_0, s.[Description] 
+0

谢谢,因为我需要它的一份报告,每月运行的,如果我创建一个真正的表,那么我需要在运行语句之前添加一个drop table语句吗? – user3347312

回答

0

似乎是你在找什么,但很难说没有从你的表的样本数据集或DDL。

Select distinct 
    m.ITMNO_0, 
    s.[Description], 
    max(s.TranDate) last_Transaction_Date 
from ITEMMASTER as m 
join SalesDataMart s on m.ITMNO_0 = s.ItemID 
Where not exists ( select distinct a.ItemID 
        from SalesDataMart a 
        where a.TranDate >= Dateadd(Month, Datediff(Month, 0, DATEADD(m, -6, current_timestamp)), 0)) 
group by m.ITMNO_0, s.[Description] 
0

假设您的物品表是ItemMaster,而您的销售交易在SalesDataMart中,您的查询将如下所示。

SELECT * 
FROM ITEMMASTER AS m 
WHERE NOT EXISTS (SELECT ItemID 
        FROM SalesDataMart AS S 
        WHERE m.ITMNO_0 = S.ItemID 
          AND TranDate > DATEADD(MONTH, -6, GETDATE()) 
        ); 

如果项目在过去6个月中售出,它会被过滤掉的查询上ItemMaster

相关问题