我需要帮助才能获得与苹果商品一起购买的订单,不包括与某些商品一起购买的订单。例如:如果客户在他的订单中购买了Apple,并且他还购买了沙拉,我需要从查询输出中排除该订单,因为我的排除项目是Salad,我的基本项目是Apple。
OrderID ItemCode ItemName Price
-------------------------------------------------------------------
1000001 100 Apple 5
1000001 101 Salad 15
1000001 102 Coffee 5.5
1000002 110 Bread 2.5
1000002 120 Banana 7.5
1000003 105 Apple 115
1000003 108 Fish 75
1000004 115 Cake 3.5
1000004 102 Apple 5.5
1000004 144 CupCake 10
答案 0 :(得分:0)
一种可能的解决方案(不是最好的)是使用Exists
和Not Exists
-
select *
from @xyz as T1
where
exists (select 1 from @xyz as T2 where T2.OrderID = T1.OrderID and T2.ItemName = 'Apple')
and
not exists (select 1 from @xyz as T3 where T3.OrderID = T1.OrderID and T3.ItemName = 'Salad')
使用Group By
-
select OrderID
from @xyz as T1
group by OrderId
having sum(case ItemName when 'Apple' then 1 when 'Salad' then -1 else 0 end) = 1
输入数据 -
declare @xyz table (OrderID int,ItemCode int,ItemName varchar(100),Price real)
insert into @xyz
select 1000001, 100, 'Apple' ,5 union all
select 1000001, 101, 'Salad' ,15 union all
select 1000001, 102, 'Coffee' ,5.5 union all
select 1000002, 110, 'Bread' ,2.5 union all
select 1000002, 120, 'Banana' ,7.5 union all
select 1000003, 105, 'Apple' ,115 union all
select 1000003, 108, 'Fish' ,75 union all
select 1000004, 115, 'Cake' ,3.5 union all
select 1000004, 102, 'Apple' ,5.5 union all
select 1000004, 144, 'CupCake' ,10