SQL:选择列值至少出现N次的行?

时间:2011-04-22 21:39:27

标签: sql select

假设我有一个带有两列的SQL表“Celebrities”:“fname”和“lname”:

fname    | lname    
---------+-------  
Bill     | Clinton
Bill     | Gates
George   | Bush
George   | Clinton
Barack   | Obama

我想编写一个查询,该查询返回表中每个人的名字和姓氏,其姓氏在“lname”列中至少出现两次。我该如何编写这个SQL查询?

3 个答案:

答案 0 :(得分:59)

SELECT fname, lname FROM Celebrities 
WHERE lname IN 
 (SELECT lname FROM Celebrities 
  GROUP BY lname HAVING COUNT (lname) >1)

答案 1 :(得分:9)

使用JOIN:

SELECT a.*
  FROM CELEBRITIES a
  JOIN (SELECT c.lname
          FROM CELEBRITIES c
      GROUP BY c.lname
        HAVING COUNT(*) >= 2) b ON b.lname = a.lname

使用EXISTS:

SELECT a.*
  FROM CELEBRITIES a
 WHERE EXISTS (SELECT NULL
                 FROM CELEBRITIES c
                WHERE c.lname = a.lname
             GROUP BY c.lname
               HAVING COUNT(*) >= 2) 

答案 2 :(得分:3)

select fname, lname
from 
  (
    select fname, lname, count(*) over(partition by lname) as lcount
    from Celebrities
  ) as S
where lcount > 1

在SQL Server 2008中测试。可能在支持count(*) over(...)

的其他DBMS中工作