3

我有一张这样的桌子

╔════╦════════╦═════════════╦═════════════════╗
║ 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 ║
╚════╩════════╩════════╩═════════════════╝
4

1 回答 1

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
于 2013-02-05T06:05:04.920 回答