【问题标题】:SQL: Issue with finding unique customers of shopsSQL:寻找商店的唯一客户的问题
【发布时间】:2013-03-13 08:50:26
【问题描述】:

我是 SQL 新手,我想编写一个查询来查找任何特定商店的唯一客户。 例如: SH1 店有 10 位客户注册,10 - 3 位客户也注册到其他一些商店。我想要一个查询,它将返回唯一的 7 位顾客到 SH1 购物。

ShopIdCustomerId 都存储在同一个表中,所以我想需要一个子查询。

谢谢, 马尤尔

样本数据:

ShopId CustomerId

  • Shop1 Cust001
  • Shop1 Cust002
  • Shop1 Cust003
  • Shop2 Cust002
  • Shop3 Cust004
  • Shop4 Cust002

在上面的示例中,如果我对商店 ID Shop1 运行查询,我应该得到 Cust001、Cust003 作为回报,它们是 Shop1 独有的,而不是 Cust002,因为它与其他商店 ID 相关联。

【问题讨论】:

  • 你能展示你的表结构和一些示例数据(你有什么和你期望什么)吗?

标签: mysql sql group-by subquery having-clause


【解决方案1】:

我猜你可以这样做

select distinct customerId from tablename where shopId = 'SH1' and customerId not in (select customerId from tablename where shopId<>'SH1');

【讨论】:

  • 这将给出所有 10 个客户 ID,而我的要求是只找到 7 个与任何其他商店 ID 没有关联的客户 ID(如上例所示)。
  • @user1696688 你能试试这个查询吗? select distinct customerId from tablename where shopId = 'SH1' and customerId not in (select customerId from tablename where shopId&lt;&gt;'SH1');
  • 谢谢..这正是我想要的:-)
  • @user1696688,Ajo Koshy:伙计们,如果接受的建议是评论中提出的建议,那么你们中的某个人应该将其编辑为答案。否则接受目前的答案是没有意义的,因此会非常令人困惑。
【解决方案2】:

如果你也想知道他们注册的商店

SELECT CustomerID, 
    ShopID
    FROM shop
    WHERE CustomerID IN (
        SELECT CustomerID
            FROM shop 
            GROUP BY CustomerID 
            HAVING COUNT(ShopID) = 1)

【讨论】:

    【解决方案3】:

    您需要独特的客户

    SELECT CUSTID FROM SHOP GROUP BY CUSTID HAVING( COUNT(SHOPID) = 1)
    

    【讨论】:

      猜你喜欢
      • 2016-11-09
      • 2023-02-07
      • 1970-01-01
      • 2019-08-27
      • 1970-01-01
      • 2020-08-08
      • 1970-01-01
      • 2022-10-02
      • 2016-09-11
      相关资源
      最近更新 更多