Skip to content
Advertisement

MySQL: Select newest two rows per Group

I have a table like this:

I need the “newest” two rows per DeviceID, where a bigger ID means newer. Right now, I’m selecting the newest row per Device via this query:

And in a loop, where I output the data, I select the second latest row for every deviceId in an individual query, which is kinda slow/dirty:

Is there a way to combine both queries or at least, in one query, select the second row for every deviceId from query 1?

Thanks

Advertisement

Answer

You can try using row_number()

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement