从MySQL获取每个人的最新记录

时间:2013-02-05 05:58:24

标签: mysql sql greatest-n-per-group

我有一张这样的表

╔════╦════════╦═════════════╦═════════════════╗
║ PK ║  NAME  ║   DEGREE    ║ YEAR_OF_PASSING ║
╠════╬════════╬═════════════╬═════════════════╣
║  1 ║ Shrey  ║ B.E.        ║            2004 ║
║  2 ║ Shrey  ║ High School ║            2000 ║
║  3 ║ Gaurav ║ B.E.        ║            2000 ║
║  4 ║ Gaurav ║ M.Sc.       ║            2002 ║
╚════╩════════╩═════════════╩═════════════════╝

如何查询获取每个人最新学位的结果集,如下所示?

╔════╦════════╦════════╦═════════════════╗
║ PK ║  NAME  ║ DEGREE ║ YEAR_OF_PASSING ║
╠════╬════════╬════════╬═════════════════╣
║  1 ║ Shrey  ║ B.E.   ║            2004 ║
║  4 ║ Gaurav ║ M.Sc.  ║            2002 ║
╚════╩════════╩════════╩═════════════════╝

1 个答案:

答案 0 :(得分:5)

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  Name, MAX(Year_Of_Passing) max_val
            FROM tableName
            GROUP BY Name
        ) b ON  a.name = b.name AND
                a.Year_Of_Passing = b.max_val

更新1

SELECT  a.*
FROM    tableName a
        INNER JOIN
        (
            SELECT  Name, MAX(Year_Of_Passing) max_val, MAX(PK) max_pk
            FROM tableName
            GROUP BY Name
        ) b ON  a.name = b.name AND
                CASE WHEN b.max_val IS NULL
                     THEN a.pk = max_PK
                     ELSE a.Year_Of_Passing = b.max_val 
                  END