2013-03-20 46 views
1

我试图写一个查询,列出所有在德克萨斯州从单一商店购买商品的顾客。SQL Server如何查找从每家商店购买产品的客户?

因此,这里有4个表及其属性:

Customers: 
customerID, CustomerName 

Purchases: 
CustomerID, ProductID 

StoresInventory: 
StoreID, ProductID 

StoreLocation: 
StoreID, State 

我可以返回得克萨斯州的商店的查询,但我不知道如何检查,如果客户已经购买的产品从所有这些商店。另外,我不能使用countaggregation。 任何人都知道如何做到这一点?

+1

什么具有u试过吗? – DevT 2013-03-20 04:11:29

+0

那么,我已经尝试使用子查询,列出德克萨斯州的商店,但是,我不知道如何完全使用这个子查询返回结果,只有当它匹配。我写过的查询返回从德州至少一家商店购买的所有客户,这是不正确的。 – user2189190 2013-03-20 05:13:04

回答

1

除非ProductID对于商店是唯一的;您想要的数据不会存储在架构中。您知道客户购买什么产品和什么商店存储这些产品,但您没有存储客户从哪个商店购买产品。

+0

是的,假设ProductID对于商店是唯一的。因此,您可以通过productID获取商店信息。对不起,我试图简化这个例子。 – user2189190 2013-03-20 05:05:01

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

如何在不使用计数的情况下执行此操作? – user2189190 2013-03-20 05:13:39

相关问题