我想创建一个视图,我想要查看过去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]
谢谢,因为我需要它的一份报告,每月运行的,如果我创建一个真正的表,那么我需要在运行语句之前添加一个drop table语句吗? – user3347312