获取已购买的订单的过滤查询输出以及某些项目,不包括与其一起购买的某些项目

时间:2018-04-19 12:53:57

标签: sql sql-server sql-server-2012

我需要帮助才能获得与苹果商品一起购买的订单,不包括与某些商品一起购买的订单。例如:如果客户在他的订单中购买了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 

1 个答案:

答案 0 :(得分:0)

一种可能的解决方案(不是最好的)是使用ExistsNot 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