查找所有购买的产品以及特定项目

时间:2017-08-05 14:01:51

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

我想编写一个查询来查找与我的订单表中的products等特定项目一起购买的所有coffee,我有一个订单表,如下所示:

    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               Meat                115 
    1000003          108               Fish                75 
    1000004          115               Cake                3.5 
    1000004          102               Coffee              5.5 
    1000004          144               CupCake             10 

那么我想如何得到结果,记住OrderID如“1000001”是一个订单等等?!

3 个答案:

答案 0 :(得分:1)

这是一种方法..

Select * from 
(
Select *,
       cofExistence = max(case when ItemName = 'Coffee' then ItemName end)
                          Over(Partition by OrderID) 
from yourtable 
) a
where cofExistence = 'Coffee'

答案 1 :(得分:1)

我的第一个想法是自我加入:

select tother.itemName, count(*) as NumOrders
from t join
     t tother
     on t.orderid = tother.orderid and
        t.itemName = 'Coffee' and
        tother.itemName <> 'Coffee'
group by tother.itemName
order by count(*) desc;

对于单个产品,您可以使用窗口函数执行相同的操作:

select t.itemName, count(*) as NumOrders
from (select t.*,
             max(case when itemName = 'Coffee' then 1 else 0 end) as hasCoffee
      from t
     ) t
where t.itemName <> 'Coffee'  -- probably not interested in coffee in the output
group by t.itemName
order by count(*) desc;

自我加入可以更容易地推广到多个产品。

答案 2 :(得分:1)

另一个选择(只是为了好玩)是一个动态的支点。

示例

Declare @Fetch varchar(100) = 'Coffee'

Declare @SQL varchar(max) = '
Select *
 From (
        Select OrderID    -- << Remove if you want a 1 line Total
              ,ItemName
              ,Value = 1
         From YourTable A
      ) A
 Pivot (Sum([Value]) For [ItemName] in (' + Stuff((Select Distinct ','+QuoteName(ItemName) 
                                                    From  YourTable
                                                    Where OrderID in (Select Distinct OrderID from YourTable Where ItemName =@Fetch)
                                                    Order By 1 
                                                    For XML Path('')),1,1,'')  + ') ) p
 Where '+quotename(@Fetch)+' is not null
'
Exec(@SQL);
--Print @SQL

<强>返回

enter image description here