简体   繁体   中英

SQL: Select rows with a column value that occurs at least N times?

Suppose I have a SQL table "Celebrities" with two columns: "fname" and "lname":

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

I would like to write a query that returns the first and last name of each person in the table whose last name appears at least twice in the column "lname". How do I write this SQL query?

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

Using a 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

Using 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) 
select fname, lname
from 
  (
    select fname, lname, count(*) over(partition by lname) as lcount
    from Celebrities
  ) as S
where lcount > 1

Tested in SQL Server 2008. Might work in other DBMS that support count(*) over(...)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM