I’m trying to combine distinct and max on this table
id name surname group year
113865 JOHN RED 29 2012
112756 ANNE REDS 128 2011
111960 MATT RED 88 2011
108615 JOHN RED 29 2011
102801 JOHN REDMOND 29 2010
98152 CARL RED 36 2009
98175 MANUEL RED 36 2009
96569 JOHN RED 31 2009
95684 CARL RED 36 2008
95685 MANUEL RED 36 2008
I would like to filter for distinct name, surname in the same group with highest year
id name surname group year
113865 JOHN RED 29 2012
112756 ANNE REDS 128 2011
111960 MATT RED 88 2011
102801 JOHN REDMOND 29 2010
98152 CARL RED 36 2009
98175 MANUEL RED 36 2009
96569 JOHN RED 31 2009
what’s the right way?
You use
group byrather thandistinct:Result:
I didn’t include the
idfield, as you haven’t specified which value you want for each distinct row. If you for example want the highest id, you can usemax(id)to include it in the result.You can include the
idfield in list and MySQL will include it in the result, but the result for that field isn’t predictable. Some other databases, like MS SQL Server, won’t allow you to include it in the result without using an aggregate like for examplemax.