【问题标题】:How to select only distinct fields如何仅选择不同的字段
【发布时间】:2017-03-16 00:13:46
【问题描述】:

假设我有一张客户地址表:

CName           |   AddressLine
-------------------------------
John Smith      | 123 Nowheresville
Jane Doe        | 456 Evergreen Terrace
John Smith      | 999 Somewhereelse
Joe Bloggs      | 1 Second Ave

我想选择具有不同 AddressLine 的 CName 意味着我不想选择“John Smith”,因为它有两个地址。我该怎么做?

【问题讨论】:

  • 您的意思是“独特”而不是“独特”吗?意思是你想要所有只有一个地址行的CNames?

标签: sql sql-server


【解决方案1】:

用途:

SELECT CName
FROM Addresses
GROUP BY CName
HAVING COUNT(DISTINCT AddressLine) = 1

【讨论】:

    【解决方案2】:

    试试这个:

    SELECT a.CName
    FROM Addresses a
    GROUP BY a.CName
    HAVING COUNT(a.AddressLine) = 1
    

    【讨论】:

      【解决方案3】:

      或者,您可以使用WHERE NOT EXISTS:

      Select  CName, AddressLine
      From    YourTable   A
      Where Not Exists
      (
          Select  *
          From    YourTable   B
          Where   A.CName = B.CName
          And     A.AddressLine <> B.AddressLine
      )
      

      编辑以解决性能问题:

      Create Table Test (CName Varchar (20), AddressLine Varchar (50));
      
      Insert Test Values 
      ('John Smith', '123 Nowheresville'),
      ('Jane Doe', '456 Evergreen Terrace'),
      ('John Smith', '999 Somewhereelse'),
      ('Joe Bloggs', '1 Second Ave')
      
      
      select cname, min(AddressLine) as AddressLine
      from test
      group by cname
      having count(*) = 1;
      
      Select  CName, AddressLine
      From    Test   A
      Where Not Exists
      (
          Select  *
          From    Test   B
          Where   A.CName = B.CName
          And     A.AddressLine <> B.AddressLine
      );
      

      执行计划:

      【讨论】:

      • 这种方法的权衡是它需要correlate subquery。但它会起作用。
      • @destination-data 虽然它确实使用相关子查询来确定记录的存在,但生成的执行计划实际上比GROUP BY HAVING 替代方案更有效。 (见编辑。)
      • 不错!很难与执行计划争论。添加该评论我感觉很糟糕,这并不是批评。我只是想向 OP 以及其他来这里寻求帮助的人强调这个概念。
      【解决方案4】:

      您可以通过以下方式获得不同的行:

      select cname, min(AddressLine) as AddressLine
      from t
      group by cname
      having count(*) = 1;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-09-16
        • 2021-01-10
        • 2011-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多