SQL Server如何找到从每家商店购买产品的客户?
我正在尝试编写一个查询,列出从德克萨斯州每家商店购买商品的所有客户 下面是4个表及其属性:SQL Server如何找到从每家商店购买产品的客户?,sql,sql-server,Sql,Sql Server,我正在尝试编写一个查询,列出从德克萨斯州每家商店购买商品的所有客户 下面是4个表及其属性: Customers: customerID, CustomerName Purchases: CustomerID, ProductID StoresInventory: StoreID, ProductID StoreLocation: StoreID, State 我可以通过查询返回德克萨斯州的所有商店,但我不确定如何检查客户是否从所有这些商店购买了产品。此外,我不能使用计数或聚合。 有人
Customers:
customerID, CustomerName
Purchases:
CustomerID, ProductID
StoresInventory:
StoreID, ProductID
StoreLocation:
StoreID, State
我可以通过查询返回德克萨斯州的所有商店,但我不确定如何检查客户是否从所有这些商店购买了产品。此外,我不能使用计数
或聚合
。
有人知道怎么做吗?除非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')
是的,假设ProductID对于商店是唯一的。因此,您可以通过productID获取门店信息。抱歉,我试图简化这个示例。我尝试过使用一个子查询来列出德克萨斯州的商店,但是,我不知道如何准确地使用这个子查询来返回匹配的结果。我写的查询返回了至少从德克萨斯州一家商店购买的所有客户,这是不正确的。如果不使用count,我将如何执行此操作?
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);