簡體   English   中英

SQL Server如何查找從EACH商店購買產品的客戶?

[英]SQL Server How to Find the customers who have bought a product from EACH store?

我正在嘗試編寫一個查詢,該查詢將列出從得克薩斯州的每個商店購買商品的所有客戶。

因此,這里有4個表格及其屬性:

Customers:
customerID, CustomerName 

Purchases:
CustomerID, ProductID 

StoresInventory:
StoreID, ProductID

StoreLocation:
StoreID, State

我可以進行查詢以返回德克薩斯州的所有商店,但是我不確定如何檢查客戶是否從所有這些商店購買了產品。 另外,我不能使用countaggregation 有人知道怎么做嗎?

除非ProductID對商店是唯一的; 所需的數據未存儲在架構中。 您知道什么客戶購買了什么產品,什么商店存儲了這些產品,但是您沒有存儲客戶從哪個商店購買了產品。

嘗試這樣的事情:

Select c.CustomerId From Customers c
Inner Join Purchases p on C.CustomerId=p.CustomerId
Inner Join StoresInventory s on s.ProductID=p.ProductID
Group By c.CustomerId
Having COUNT(Distinct s.StoreId)=(Select Count(Distinct StoreId) From StoreLocation Where State='Texas')
SELECT a.customerid
FROM purchases a
JOIN store_inventory b
    ON a.productid=b.productid
GROUP BY  a.customerid
HAVING count(distinct storeid)= 
    (SELECT count(*)
    FROM store_location s);

暫無
暫無

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

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