This question already has answers here:
How can I SELECT rows with MAX(Column value), DISTINCT by another column in SQL?
(17个答案)
两年前关闭。
我有两张表,如下所示:
            Table Name : scores
+-------+-----------+--------------+-----------+
| UNID  |   name    |    score     |   PRID    |
+-------+-----------+--------------+-----------+
|  1    |  name_1   |      93      |        1  |
|  2    |  name_2   |      71      |        1  |
|  3    |  name_3   |      53      |        2  |
|  4    |  name_4   |      82      |        2  |
|  5    |  name_5   |      31      |        2  |
|  6    |  name_6   |      68      |        3  |
+-------+-----------+--------------+-----------+

以及
                  Table Name : user_dir
+-------+-----------+--------------+-----------+
| PRID  |   fname   |    city      |   gender  |
+-------+-----------+--------------+-----------+
|  1    |  fname1   |      XX      |        m  |
|  2    |  fname2   |      YY      |        f  |
|  3    |  fname3   |      ZZ      |        f  |
+-------+-----------+--------------+-----------+

对于来自用户目录的任何给定PRID,如何获取与该PRID的最高得分值相对应的整行?
例如,对于PRID为2的用户“fname2”,我希望将整行(而不仅仅是score的值)拉取如下:
 +-------+-----------+--------------+-----------+
 | UNID  |   name    |    score     |   PRID    |
 +-------+-----------+--------------+-----------+
 |  4    |  name_4   |      82      |        2  |

我用那一行的“max”函数尝试了这个,但是它给了我用那个PRID找到的第一行,以及正确的(max)得分值,如下所示:
 +-------+-----------+--------------+-----------+
 | UNID  |   name    |    score     |   PRID    |
 +-------+-----------+--------------+-----------+
 |  3    |  name_3   |      82      |        2  |

编辑:我误解了我的要求,最终的结果需要有相应的“名称”值来表示最高的分数,而不是最高的分数本身。
所以实际的最终结果是:
+-------+-----------+--------------+-----------+
| PRID  |   name    |    fname     |   score   |
+-------+-----------+--------------+-----------+
|  1    |  fname1   |    name_1    |     93    |
|  2    |  fname2   |    name_4    |     82    |
|  3    |  fname3   |    name_6    |     68    |

最佳答案

SELECT s.*
FROM scores s
WHERE PRID = 2 AND score = (SELECT MAX(score) FROM scores WHERE PRID = 2)

如果要获取包含每个PRID的所有最高分数的记录,则可以尝试以下操作:
SELECT s.*
FROM scores s
WHERE score = (SELECT MAX(score) FROM scores s1 WHERE s.PRID = s1.PRID)

10-08 17:25