2016-03-29 82 views
0

我試圖確定有多少人購買了可以存在的所有不同產品對中的一對商品。例如。我有三種產品,A,B,C和我想確定有多少%的客戶在每個國家/地區擁有兩種產品的客戶數量中購買了A和B,B和C以及A​​和C。SQL:跨產品

我的表格如下所示。

Customer | Country | Product 
1  | US | A 
1  | US | B 
2  | CA | A 
2  | CA | C 
3  | US | A 
3  | US | C 
4  | US | B 
5  | US | A 

請注意,客戶只能屬於一個國家。

我的期望的輸出是:

Country | Pair | % 
US  | A_B | 25%  
US  | B_C | 0% 
US  | A_C | 25% 
CA  | A_B | 0%  
CA  | B_C | 0% 
CA  | A_C | 100% 

的%基本上是比

(# of unique customers who bought Product1 and Product2)/ 
(# of unique customers who bought Product1 or Product2) 

由國家。

因此,例如,在美國A_B我們有4個誰買了這些AB但只買了1兩AB所以比1/4客戶。

有沒有一個很好的解決方案,如果我有一個大數目,任意數量的配對可以擴展?

+1

您是否需要每個國家的輸出?或者「請注意,客戶只能屬於一個國家」的意義何在? – JanR

+0

所以,你已經完全改變了這個問題。以下所有答案現在都不相關。你應該已經創建了一個新的問題,因爲截至目前似乎答案不會產生預期的結果 – cha

回答

0

如果你只是想有一個產品對,你可以用一個簡單的join

select t1.product, t2.product, count(distinct customer) 
from t t1 join 
    t t2 
    on t1.customer = t2.customer 
group by t1.product, t2.product; 

對於所有對,您可以將其用作子查詢,然後返回到所有產品對的列表:

with pp as (
     select t1.product as product1, t2.product as product2, count(distinct customer) as cnt 
     from t t1 join 
      t t2 
      on t1.customer = t2.customer 
     group by t1.product, t2.product 
    ) 
select p1.product, p2.product, pp.cnt 
from (select distinct product from t) p1 cross join 
    (select distinct product from t) p2 left join 
    pp 
    on pp.product1 = t1.product and pp.product2 = t2.product; 
+0

謝謝你的幫助。我無法找到一種方法來改變上面的查詢來獲得我想要的結果,所以我改變了我的問題來包含我的整個目標。 – Black

0

首先,使用JOIN得到Product的所有配對。然後使用APPLYCOUNTCustomer小號誰既帶來了Product

WITH CteProduct AS(
    SELECT DISTINCT 
     Prod1 = t1.Product, 
     Prod2 = t2.Product 
    FROM tbl t1 
    INNER JOIN tbl t2 
     ON t1.Product < t2.Product 
) 
SELECT 
    Parir = c.Prod1 + '_' + c.Prod2, 
    Number = ISNULL(x.Number, 0) 
FROM CteProduct c 
OUTER APPLY(
    SELECT 
     t.Customer, 
     Number = COUNT(DISTINCT t.Country) 
    FROM tbl t 
    WHERE t.Product IN(c.Prod1, c.Prod2) 
    GROUP BY t.Customer 
    HAVING COUNT(DISTINCT t.Product) = 2 

) x; 

ONLINE DEMO

+0

感謝您的幫助。我如何能夠通過國家和產品對來改變這一點? – Black

+0

對不起,我誤讀了要求。將Number = COUNT(DISTINCT Customer)'更改爲'Number = COUNT(DISTINCT Country)' –

+0

這似乎是最直接的。不過,我認爲這不會按照我的新編輯起作用,因爲我不想指望國家。請參閱我的編輯。 – Black