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!
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.
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With