I have a table with id, city_id, and stock which looks like this.
| id | city_id | stock |
|---|---|---|
| 1 | 1 | 1000 |
| 2 | 2 | 500 |
| 3 | 3 | 11000 |
| 4 | 2 | 600 |
| 5 | 3 | 12000 |
| 6 | 1 | 2000 |
| 9 | 3 | 13000 |
| 10 | 1 | 3000 |
| 11 | 1 | 4000 |
| 12 | 2 | 700 |
To select the latest stock values for each city_id I used the following query, which works fine.
SELECT `stock`
FROM `stock_table`
WHERE id in ( SELECT MAX(id)
FROM `stock_table`
GROUP BY city_id
);
It returns
| stock |
|---|
| 13000 |
| 4000 |
| 700 |
Now I want to select 2nd latest stock entry for each city_id. So the output should be like the following table.
| stock |
|---|
| 12000 |
| 3000 |
| 600 |
Any help is greatly appreciated. Thanks!