53

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 'Smith', 4 with 'Johnson', and 1 with 'Potter'. My query should show the records of those with the lastnames Smith, and Johnson since these values occur more than or equal to 3 times.

Can anyone point me to this? I was thinking of using COUNT() but I can't seem to think how to apply it?

iDev
  • 23,310
  • 7
  • 60
  • 85
Smiley
  • 3,207
  • 13
  • 49
  • 66

7 Answers7

69

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

Andrii Kovalchuk
  • 4,351
  • 2
  • 36
  • 31
47

For SQL Server 2005+

;WITH T AS
(
SELECT *, 
       COUNT(*) OVER (PARTITION BY Lastname) as Cnt
FROM Students
)
SELECT * /*TODO: Add column list. Don't use "*"                   */
FROM T
WHERE Cnt >= 3
Martin Smith
  • 438,706
  • 87
  • 741
  • 845
14

For MySQL:

SELECT lastname AS ln 
    FROM 
    (SELECT lastname, count(*) as Counter 
     FROM `students` 
     GROUP BY `lastname`) AS tbl WHERE Counter > 2
gkrogers
  • 8,126
  • 3
  • 29
  • 36
Till
  • 3,084
  • 17
  • 18
11

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
)
Kudehinbu Oluwaponle
  • 1,045
  • 11
  • 11
4
SELECT LASTNAME, COUNT(*)
FROM STUDENTS
GROUP BY LASTNAME
ORDER BY COUNT(*) DESC
garnertb
  • 9,454
  • 36
  • 38
3

For postgresql:

SELECT * AS rec 
FROM (
    SELECT lastname, COUNT(*) AS counter 
    FROM students 
    GROUP BY lastname) AS tbl 
WHERE counter > 1;
Hamza Abdaoui
  • 2,029
  • 4
  • 23
  • 36
embuc
  • 465
  • 5
  • 5
-1

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)
Maryam
  • 41
  • 7
  • Please explain why your solution works for the OP's question. Link only answers are not considered good practice. Please see https://stackoverflow.com/help/how-to-answer – Marcello B. Feb 14 '20 at 19:31