Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Select Distinct with Conditional

Tags:

sql

mysql

Table1 has columns (id, a, b, c, group). There are several rows that have the same group, but id is always unique. I would like to SELECT group,a,b FROM Table1 WHERE the group is distinct. However, I would like the returned data to be from the row with the greatest id for that group.

Thus, if we have the rows

(id=10, a=6, b=40, c=3, group=14)  
(id=5, a=21, b=45, c=31, group=230)  
(id=4, a=42, b=65, c=2, group=230)

I would like to return these 2 rows:

[group=14, a=6,b=40] and   
[group=230, a=21,b=45] (because id=5 > id=4)

Is there a simple SELECT statement to do this?

like image 354
nedblorf Avatar asked Oct 15 '25 16:10

nedblorf


1 Answers

Try:

select grp, a, b
  from table1 where id in
    (select max(id) from table1 group by grp)
like image 99
Pablo Santa Cruz Avatar answered Oct 17 '25 04:10

Pablo Santa Cruz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!