Optimize groupwise maximum query

Assuming relatively few rows in options for many rows in records. Typically, you would have a look-up table options that is referenced from records.option_id, ideally with a foreign key constraint. If you don’t, I suggest to create one to enforce referential integrity: CREATE TABLE options ( option_id int PRIMARY KEY , option text UNIQUE NOT … Read more

Finding running maximum by group

We can try data.table. Convert the ‘data.frame’ to ‘data.table’ (setDT(df1)), grouped by ‘group’ , we get the cummax of ‘var’ and assign (:=) it to a new variable (‘curMax’) library(data.table) setDT(df1)[, curMax := cummax(var), by = group] As commented by @Michael Chirico, if the data is not ordered by ‘time’, we can do that in … Read more

Retrieving the last record in each group – MySQL

MySQL 8.0 now supports windowing functions, like almost all popular SQL implementations. With this standard syntax, we can write greatest-n-per-group queries: WITH ranked_messages AS ( SELECT m.*, ROW_NUMBER() OVER (PARTITION BY name ORDER BY id DESC) AS rn FROM messages AS m ) SELECT * FROM ranked_messages WHERE rn = 1; This and other approaches … Read more