0

I have a table with a unix time stamp and a thing description. The table will have multiple entries for each thing, all with different time stamps. I need to select the last five time stamps for each thing.

If I have 100 rows for thing A, 130 rows for thing B and 20 rows for thing C I want to see the last 5 for each thing - the query should return 15 records.

I've tried limit but that gives me the last five in the query.

Any suggestions would be appreciated.

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
Eric Snyder
  • 1,816
  • 3
  • 22
  • 46

2 Answers2

0

You could use ROW_NUMBER (MySQL 8.0):

SELECT *
FROM (SELECT *,ROW_NUMBER() OVER(PARTITION BY col1 ORDER BY time_col DESC) rn
      FROM tab) sub
WHERE rn <= 5;
Lukasz Szozda
  • 162,964
  • 23
  • 234
  • 275
0

For 100 rows, you can easily do:

select t.*
from t
where (select count(*)
       from t t2
       where t2.thing = t.thing and t2.timestampe <= t.timestamp
      ) <= 5;
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786