簡體   English   中英

查找按客戶SQL分組購買多個產品的次數

[英]Find number of times multiple products were purchased grouped by Customer SQL

我試圖運行查詢以查找客戶訂購產品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        

請仔細查看如何計算“ 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表和列是猜測,因為您沒有發布結構。 根據需要更改它們。

使用每個產品的派生表的解決方案。 第一個派生表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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM