我们使用的软件有两个订单表,Orders和OrderItems。 我正在尝试对数据库运行查询以显示哪些项目在一段时间内没有销售。 这就是我所拥有的,但它不起作用(它会带来所有记录)
SELECT
OrderItem.Name,
OrderItem.SKU,
[Order].OrderDate
FROM
[Order]
INNER JOIN OrderItem ON [Order].OrderID = OrderItem.OrderID
WHERE
(OrderItem.SKU NOT IN
(SELECT DISTINCT OrderItem.SKU WHERE ([Order].OrderDate BETWEEN '2014-09-08' AND '2014-01-01')))
答案 0 :(得分:2)
您实际上可以使用having
子句执行此操作:
SELECT oi.Name, oi.SKU, max(o.OrderDate) as lastOrderDate
FROM [Order] o INNER JOIN
OrderItem oi
ON o.OrderID = oi.OrderID
GROUP BY oi.Name, oi.SKU
HAVING sum(case when o.OrderDate between '2014-01-01' and '2014-09-08' then 1 else 0 end) = 0;
如果您在今年之前只是在寻找订单,那么将having
子句写成:
HAVING max(o.OrderDate) < '2014-01-01'
答案 1 :(得分:1)
翻转你的约会。它应该是[结束日期]之间的[开始日期]
WHERE (OrderItem.SKU NOT IN
(SELECT DISTINCT OrderItem.SKU
WHERE ([Order].OrderDate BETWEEN '2014-01-01' AND '2014-09-08')))
答案 2 :(得分:0)
以下内容如何:
SELECT oi.Name, oi.SKU, o.OrderDate
FROM [Order] o
INNER JOIN OrderItem oi ON o.OrderID = oi.OrderID
WHERE oi.SKU NOT IN
(
SELECT os.SKU
FROM [Order] os
INNER JOIN OrderItem ois ON os.OrderID = ois.OrderID
WHERE os.OrderDate BETWEEN '2014-01-01' AND '2014-09-08'
)
您必须加入子查询中的OrderItem
表才能获得SKU
。
答案 3 :(得分:0)
您的查询看起来像是颠倒了#39。
SELECT DISTINCT SKU FROM OrderItem oi
WHERE NOT EXISTS
(SELECT 1 FROM Order o
JOIN OrderItem oi2 ON o.OrderID = oi2.OrderID
WHERE oi2.SKU = oi.SKU
AND o.OrderDate BETWEEN '2014-01-01' AND '2014-09-08' );
答案 4 :(得分:0)
理想情况下,您应该有另一个包含不同项目的表格,因此您可以编写以下查询以查看在特定时期内未售出的商品(可能从未销售过)。
select i.SKU from items
where not exists (
select 1 from OrderItem oi
join Order o on o.OrderID = oi.OrderID
where oi.SKU = i.SKU
and o.OrderDate BETWEEN '2014-01-01' and '2014-09-08'
)
如果您没有这样的表格,您可以选择在某个时间点订购的所有产品,但不能在其他时间段内订购
select i.SKU from (
select distinct oi.SKU from OrderItem oi
) i
where not exists (
select 1 from OrderItem oi
join Order o on o.OrderID = oi.OrderID
where oi.SKU = i.SKU
and o.OrderDate BETWEEN '2014-01-01' and '2014-09-08'
)