1

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

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

Customers:
customerID, CustomerName 

Purchases:
CustomerID, ProductID 

StoresInventory:
StoreID, ProductID

StoreLocation:
StoreID, State

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

4

3 回答 3

2

尝试这样的事情:

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')
于 2013-03-20T04:45:55.020 回答
1

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

于 2013-03-20T04:36:00.923 回答
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);
于 2018-11-26T06:30:49.080 回答