【问题标题】:Get a filtered Query Output for Orders bought along with certain items excluding certain items bought along with them获取与某些项目一起购买的订单的过滤查询输出,不包括与其一起购买的某些项目
【发布时间】:2018-04-20 00:00:57
【问题描述】:

我需要帮助才能获得与苹果商品一起购买的订单,但不包括与某些商品一起购买的订单。例如:如果客户在他的订单中购买了一个苹果,并且他还购买了沙拉,我需要从我的查询输出中排除该订单号,因为我的排除项目是沙拉,而我的基本项目是苹果。

    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 

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-21
      • 2022-10-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多