2017-08-05 62 views
-1

一起購買我想編寫一個查詢來發現我的訂單表與特定的項目一起被購買了如coffee所有products,我有如下的順序表:找到所有的產品都與特定項目

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」就是一個命令等等?!

+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

我首先想到的是自聯接:

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; 

自聯接更容易推廣到多個產品。

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 [email protected]) 
                Order By 1 
                For XML Path('')),1,1,'') + ')) p 
Where '+quotename(@Fetch)+' is not null 
' 
Exec(@SQL); 
--Print @SQL 

返回

enter image description here