I have a table with isin (test), date (Date), and amount (int).
I am trying to get the amount of the last 2 dates per isin.
Someone can tell me the trick please?
Rick James
80.7k5 gold badges52 silver badges119 bronze badges
-
Last 2 dates are first 2 dates when the ordering is reversed.Akina– Akina2024年04月11日 04:25:12 +00:00Commented Apr 11, 2024 at 4:25
-
See the tag I added or Groupwise-MaxRick James– Rick James2024年04月27日 04:29:52 +00:00Commented Apr 27, 2024 at 4:29
1 Answer 1
With MySQL 8 you can use a CTE with then Window function ROW_NUMBER to get your wanted data
WITH CTE AS(SELECT
isin , date , amount ,
ROW_NUMBER() OVER(PARTITION BY isin ORDER BY date DESC) rn
FROM mytable)
SELECT
isin , date , amount
FROM CTE
WHERE rn <= 2
ORDER BY isin, rn
answered Apr 10, 2024 at 21:24
lang-sql