-1

I have a mysql query to select the most recent record for each grouped using the below query

SELECT *
FROM tbl_prices
WHERE id IN (
    SELECT MAX(id)
    FROM tbl_prices
    GROUP BY instrument
);

but now I need to get the most recent 2 records for each grouped column. The reason being I need to compare the difference between the latest 2 records to perform additional functionality on the result.

Should I create 2 queries to get the results and if so how would I get the most recent - 1

I've had a look at this SO post (Retrieving the last record in each group - MySQL) but it doesn't seem to fit my requirements as it's still only the latest record for each group.

user1020496
  • 99
  • 1
  • 9

1 Answers1

1

you try to use row_number().

select * from (
select * , row_number() over(partition by instrument order by id desc) as row_num from from tbl_prices
) p where p.row_num <= 2
cherful
  • 179
  • 4