Select row by max value in group in a pandas dataframe

A standard approach is to use groupby(keys)[column].idxmax(). However, to select the desired rows using idxmax you need idxmax to return unique index values. One way to obtain a unique index is to call reset_index. Once you obtain the index values from groupby(keys)[column].idxmax() you can then select the entire row using df.loc: In [20]: df.loc[df.reset_index().groupby([‘F_Type’])[‘to_date’].idxmax()] Out[20]: … Read more

SQL server select distinct rows using most recent value only

One way select t1.* from (select ForeignKeyId,AttributeName, max(Created) AS MaxCreated from YourTable group by ForeignKeyId,AttributeName) t2 join YourTable t1 on t2.ForeignKeyId = t1.ForeignKeyId and t2.AttributeName = t1.AttributeName and t2.MaxCreated = t1.Created See also Including an Aggregated Column’s Related Values for 5 different ways to do this kind of query

Laravel Eloquent group by most recent record

To get latest record per customer among for each city based on created_at you can use a self join DB::table(‘yourTable as t’) ->select(‘t.*’) ->leftJoin(‘yourTable as t1’, function ($join) { $join->on(‘t.Customer’,’=’,’t1.Customer’) ->where(‘t.City’, ‘=’, ‘t1.City’) ->whereRaw(DB::raw(‘t.created_at < t1.created_at’)); }) ->whereNull(‘t1.id’) ->get(); In plain SQL it would be something like select t.* from yourTable t left join yourTable … Read more

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