SQL Server如何查找从EACH商店购买产品的客户?

时间:2013-03-20 03:57:13

标签: sql sql-server

我正在尝试编写一个查询,列出从德克萨斯州的每家商店购买商品的所有客户。

所以这里有4个表及其属性:

Customers:
customerID, CustomerName 

Purchases:
CustomerID, ProductID 

StoresInventory:
StoreID, ProductID

StoreLocation:
StoreID, State

我可以查询返回德克萨斯州的所有商店,但我不确定如何检查客户是否从所有这些商店购买了产品。另外,我无法使用countaggregation。 有谁知道怎么做?

3 个答案:

答案 0 :(得分:1)

除非ProductID对商店是唯一的;您想要的数据不存储在架构中。您知道客户购买了哪些产品以及商店库存的产品,但您没有存储客户购买产品的商店。

答案 1 :(得分:1)

尝试这样的事情:

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')

答案 2 :(得分:0)

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);
相关问题