Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

select

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?

like image 649
Vivian River Avatar asked Apr 22 '11 21:04

Vivian River


People also ask

How do I select a row with minimum value in SQL?

To select data where a field has min value, you can use aggregate function min(). The syntax is as follows. SELECT *FROM yourTableName WHERE yourColumnName=(SELECT MIN(yourColumnName) FROM yourTableName);

How do I select N random rows in SQL?

To get a single row randomly, we can use the LIMIT Clause and set to only one row. ORDER BY clause in the query is used to order the row(s) randomly. It is exactly the same as MYSQL. Just replace RAND( ) with RANDOM( ).

What is at least in SQL?

What is LEAST() in SQL? The LEAST() function returns the smallest value from a list of arguments.

How do you select nth value in SQL?

ROW_NUMBER (Window Function) ROW_NUMBER (Window Function) is a standard way of selecting the nth row of a table. It is supported by all the major databases like MySQL, SQL Server, Oracle, PostgreSQL, SQLite, etc.


1 Answers

SELECT fname, lname FROM Celebrities  WHERE lname IN   (SELECT lname FROM Celebrities    GROUP BY lname HAVING COUNT (lname) >1) 
like image 171
Ocaso Protal Avatar answered Sep 20 '22 04:09

Ocaso Protal