【问题标题】:SQL Server How to Find the customers who have bought a product from EACH store?SQL Server 如何找到从每个商店购买产品的客户?
【发布时间】:2013-03-20 03:57:13
【问题描述】:

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

所以这里有 4 个表和它们的属性:

Customers:
customerID, CustomerName 

Purchases:
CustomerID, ProductID 

StoresInventory:
StoreID, ProductID

StoreLocation:
StoreID, State

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

【问题讨论】:

  • 好吧,我已经尝试使用列出德克萨斯州商店的子查询,但是,我无法弄清楚如何准确地使用此子查询以仅在匹配时返回结果。我写的查询返回了从德克萨斯州至少一家商店购买的所有客户,这是不正确的。

标签: sql sql-server


【解决方案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')

【讨论】:

  • 不使用 count 怎么办?
【解决方案2】:

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

【讨论】:

  • 是的,假设 ProductID 对于商店是唯一的。所以可以通过productID获取店铺信息。抱歉,我试图简化示例。
【解决方案3】:
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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-07-30
    • 2020-10-21
    • 2015-11-10
    • 2022-10-17
    • 1970-01-01
    • 2013-09-05
    • 2011-06-08
    相关资源
    最近更新 更多