查找按客户SQL分组购买多个产品的次数

时间:2014-07-21 18:12:09

标签: sql oracle

我正在尝试运行查询以查找客户订购产品x和产品y的次数。客户必须购买产品10才能显示。如果有一种方法可以添加另一列来标记true或false,如果产品数量匹配。还有第二个表格包含客户信息。

CustomerID      ProductID
    1              10
    1              10
    1              11
    2              10
    2              9
    3              11
    3              9

结果:(请记住,如果客户没有订购Product_10,他/她将不会在结果中显示。

 Customer    Product_10   Product_11
    John          2            1
    Mike          1            0        

2 个答案:

答案 0 :(得分:2)

仔细看看" Product_10"和" Product_11"列计算;他们是你正在努力做的事情的关键。最后的HAVING会淘汰任何没有产品的客户#Product; 10"订单:

SELECT
  Customers.Customer,
  SUM(CASE WHEN Products.ProductID = 10 THEN 1 ELSE 0 END) AS Product_10,
  SUM(CASE WHEN Products.ProductID = 11 THEN 1 ELSE 0 END) AS Product_11
FROM Customers
INNER JOIN Products ON Customers.ProductID = Products.ProductID
GROUP BY Customers.Customer
HAVING SUM(CASE WHEN Products.ProductID = 10 THEN 1 ELSE 0 END) > 0

Customers表和列是猜测,因为您没有发布结构。根据需要改变它们。

答案 1 :(得分:0)

使用每个产品的派生表的解决方案。第一个派生表t10包含每个customerId购买的产品10的数量,此表是内部连接的,因此只显示至少购买1个的客户,而第二个表t11保持连接状态显示任何购买的客户。

select c.customer, t10.p10_count Product_10, 
    coalesce(t11.p11_count,0) Product_11,
    (t10.p10_count = t11.p11_count) flag
from customer c
join (select CustomerID, count(*) p10_count
    from customer_products
    where ProductID = 10
    group by CustomerID) t10 
on t10.CustomerID = c.CustomerID
left join (select CustomerID, count(*) p11_count
    from customer_products
    where ProductID = 11
    group by CustomerID) t11 
on t11.CustomerID = c.CustomerID