SQL Query To Obtain Value that Occurs more than once

前端 未结 7 1986
陌清茗
陌清茗 2020-12-08 19:26

I need to query my database to show the records inside my table where lastname occurs more than three times. Example: in my Students Table, there are 3 people with Lastname

相关标签:
7条回答
  • 2020-12-08 19:32

    The answers mentioned here is quite elegant https://stackoverflow.com/a/6095776/1869562 but upon testing, I realize it only returns the last name. What if you want to return the entire record itself ? Do this (For Mysql)

    SELECT *
    FROM `beneficiary`
    WHERE `lastname`
    IN (
    
      SELECT `lastname`
      FROM `beneficiary`
      GROUP BY `lastname`
      HAVING COUNT( `lastname` ) >1
    )
    
    0 讨论(0)
  • 2020-12-08 19:33

    From Oracle (but works in most SQL DBs):

    SELECT LASTNAME, COUNT(*)
    FROM STUDENTS
    GROUP BY LASTNAME
    HAVING COUNT(*) >= 3
    

    P.S. it's faster one, because you have no Select withing Select methods here

    0 讨论(0)
  • 2020-12-08 19:43

    For postgresql:

    SELECT * AS rec 
    FROM (
        SELECT lastname, COUNT(*) AS counter 
        FROM students 
        GROUP BY lastname) AS tbl 
    WHERE counter > 1;
    
    0 讨论(0)
  • 2020-12-08 19:43

    I think this answer can also work (it may require a little bit of modification though) :

    SELECT * FROM Students AS S1 WHERE EXISTS(SELECT Lastname, count(*) FROM Students AS S2 GROUP BY Lastname HAVING COUNT(*) > 3 WHERE S2.Lastname = S1.Lastname)
    
    0 讨论(0)
  • 2020-12-08 19:45
    SELECT LASTNAME, COUNT(*)
    FROM STUDENTS
    GROUP BY LASTNAME
    ORDER BY COUNT(*) DESC
    
    0 讨论(0)
  • 2020-12-08 19:46

    For MySQL:

    SELECT lastname AS ln 
        FROM 
        (SELECT lastname, count(*) as Counter 
         FROM `students` 
         GROUP BY `lastname`) AS tbl WHERE Counter > 2
    
    0 讨论(0)
提交回复
热议问题