2010-10-04 81 views
2

有來自花店,它看起來像如何做到這一點查詢

CustomerID  Flower 

    John    peony 
    John    lily 
    John    Lotus 

    Mary    peony 
    Mary    lily 
    Mary    chrysanthemum 

    Lisa    chrysanthemum 
    Lisa    peony 
    Lisa    kapok 

enter code here 

我想找到這些客戶的ID誰買相同的N花朵的數據表。例如,在上表中,對於牡丹和百合,購買他們兩個的顧客(對於這種情況n = 2)是約翰和瑪麗。

我找不出一個SQL語句來執行上述查詢。請幫忙。 感謝

回答

0

選擇客戶ID,花從[yourtable],其中花=「牡丹」或「百合」

你希望它是動態的?

然後可能使變量存儲過程。更多關於sp的信息here

0

自我加入怎麼樣?

SELECT 
    y.CustomerID 
FROM 
    YourTable y 
JOIN 
    YourTable y2 
ON 
    y.CustomerID = y2.CustomerId 
WHERE 
    y.Flower = "Lily" 
AND 
    y2.Flower = "Lotus" 
0

加入表格本身。

SELECT a.CustomerID, b.CustomerID, a.Flower FROM flowertable a, flowertable b WHERE a.Flower = b.Flower 
+0

這將返回'約翰| Mary |莉莉「,他想要返回像」約翰「這樣的東西百合和牡丹' – cypher 2010-10-04 11:34:31

0

你需要像這樣

select distinct(CustomerID) from mytable 
where flower in 
(select distinct(flower) from mytable group by flower having count(flower) = 2) 

可以更換你想要的任何號碼!

0

我想嘗試的存在條款,只花報告有多個不同的購買者:

select a.customerid, a.flower 
from yourtable a 
where exists 
    (select 'x' 
    from yourtable b 
    where b.customerid <> a.customerid 
    and b.flower = a.flower)