2016-03-29 38 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