Grouping by Column with Dependence on another Column

后端 未结 2 1035
无人共我
无人共我 2021-01-19 04:04

Here is a simplified look at the problem I am trying to cleanly solve via a MySQL query. This is not the actual table I am dealing with.

If I have the following ta

2条回答
  •  南笙
    南笙 (楼主)
    2021-01-19 04:44

    Try this one, the idea behind the subquery is that it gets the latest ID for each Name using MAX (aggregate function). Then join it against the table itself on the two columns of the subquery.

    SELECT  a.*
    FROM    tableName a
            INNER JOIN 
            (
                SELECT name, MAX(ID) maxID
                FROM tableName
                GROUP BY name
            ) b ON a.Name = b.Name AND
                    a.ID = b.MaxID
    
    • SQLFiddle Demo

提交回复
热议问题