我想创建一个视图,我想获得过去6个月内未售出的商品列表。我尝试了几种方法,但没有一种方法是正确的。 请指导我。 我有一个销售数据集市的表,其中包含项目号,我从另一个表中获取项目号,这是一个项目表,用于列出所有项目。 这里有两种方法: 我不能制作临时表,因为这是一个观点?
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 :(得分: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]
答案 1 :(得分: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上的查询中过滤掉