Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL select nth member of group

Tags:

mysql

group-by

If I have a USER table like

class | age -------------- 1       20     3       56 2       11 1       12 2       20 

Then I can easily get the youngest user in each class via

select class, min(age) from   user group by class; 

Similarly, by replacing min with max, I can get the oldest. But how can I get the 10th youngest (or oldest) in each class? By the way, I'm using MySql v.5.0.

Cheers,

like image 631
Dónal Avatar asked Jan 20 '09 20:01

Dónal


People also ask

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.

How do I select every nth record in SQL?

Here's the SQL query to select every nth row in MySQL. mysql> select * from table_name where table_name.id mod n = 0; In the above query, we basically select every row whose id mod n value evaluates to zero.

Can we use group by in select?

The SQL GROUP BY clause is used in a SELECT statement to collect data across multiple records and group the results by one or more columns. A SELECT statement clause that divides the query result into groups of rows, usually for the purpose of performing one or more aggregations on each group.

What is the difference between select * and select 1?

Select * from any table will fetch and display all the column in that table, while Select 1 from any table will display one row with 1 without any column name.


2 Answers

SELECT a.class, (     SELECT b.age      FROM users b      WHERE b.class = a.class     ORDER BY age      LIMIT 1,1 ) as age FROM users a GROUP BY a.class 

Would get the 2nd youngest in each class. If you wanted the 10th youngest, you'd do LIMIT 9,1 and if you wanted the 10th oldest, you'd do ORDER BY age DESC.

like image 180
Paolo Bergantino Avatar answered Sep 23 '22 15:09

Paolo Bergantino


Here N presents Nth record oldest

SELECT * FROM users k WHERE N = (SELECT              COUNT( DISTINCT age)            FROM users u            WHERE k.age >= u.age                AND k.class = u.class            GROUP BY u.class) 

and it gives Nth record youngest

SELECT * FROM users k WHERE N = (SELECT              COUNT(DISTINCT age)            FROM users u            WHERE k.age <= u.age                AND k.class = u.class            GROUP BY u.class) 
like image 42
Deval Shah Avatar answered Sep 20 '22 15:09

Deval Shah