Friday 29 March 2024

MySQL: How to Select Entire Row with MAX in Group By (Subquery Method)

 


Code : 

SELECT potential_customers.* from potential_customers where concat(potential_customers.customer_id,'-',potential_customers.next_call) IN

(SELECT concat(PC1.customer_id,'-',MAX(PC1.next_call)) FROM `potential_customers` PC1 GROUP by customer_id);

========================

Subscribe my Channel:-

http://www.youtube.com/user/SanketRooney?sub_confirmation=1


Gaming Channel:-

https://www.youtube.com/@unpoggaming9532


Gaming Instagram:- (@unpog.gaming)

https://www.instagram.com/unpog.gaming/

Facebook Page:-

https://www.facebook.com/UnpossibleNS

Twitter Account:-

https://twitter.com/UnpossiblePOG

Blog:-

https://unpossiblepog.blogspot.com/

Website:-

https://unpossiblepog.com/

========================

Hey guys, there is a limitation in MYSQL, where you use group by and wanted max value, but when you try to fetch a row ID or any other column, it fails.

For example, there is one table on the left side called “potential_customers”, and on the right side, I wrote one query which returns maximum NEXT_CALL value for each customer_id.

So, in current example I wanted row ID 2 & 6.

But if I need ID or whole row, it fails even when you use order by column_name DESC.

Thankfully there is a workaround for this which is to use the combination of subquery and concat.

First, let’s alter the query, to concat customer_id and max of next call. Remove all order by if there is any.

Put that query is sub-query by adding rounded brackets around it.

Now, write a select query before sub query, & in where condition, use concat of required column. Don’t forget to use “IN” keyword.

And as you can see, it returns row ID that we need.

You can call whole column if you want.

So that’s it. Code link is given in the description.

Thanks for watching. Like, Share and Subscribe.