Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL to get the 2nd (nth) record for each group (postgresql or mysql)

I googled and stackoverflowed high and low and not able to find any concrete solutions to show the 2nd (nth) record for each group.

Consider the following table (order by created_at desc):

----------------------------------------------
bid_id | status    | created_at
----------------------------------------------
1      | cancelled | 2015-10-03 
1      | awarded   | 2015-10-02
1      | pending   | 2015-10-01
2      | pending   | 2015-10-01
3      | denied    | 2015-10-02
3      | pending   | 2015-10-01

The result output should look like this (grouped by bid_id):

bid_id | status    | created_at
----------------------------------------------
1      | awarded   | 2014-10-02
3      | pending   | 2014-10-01

What is an efficient SQL to achieve this? Any tips are greatly appreciated!

like image 909
chadwtaylor Avatar asked Sep 04 '15 16:09

chadwtaylor


People also ask

How do I get last second record in SQL?

You need to use ORDER BY clause to get the second last row of a table in MySQL. The syntax is as follows. select *from yourTableName order by yourColumnName DESC LIMIT 1,1; To understand the above syntax, let us create a table.

How do I get the nth row in MySQL?

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.


1 Answers

You can use row_number to assign row numbers in each bi_id partition ordered by created_at column. Then you can simply select the 2nd or whichever row you need. This works in postgres as it supports window functions.

select bid_id, status, created_at
from
(
select bid_id, status, created_at,
row_number() over(partition by bid_id order by created_at desc) as rn
from tablename
) x
where x.rn = 2;
like image 163
Vamsi Prabhala Avatar answered Oct 19 '22 22:10

Vamsi Prabhala