具有最高值的SQL SELECT行,其中problem_id相同


SQL SELECT row with highest value where problem_id is the same

我正在做一个项目,在这个项目中,我必须列出每个问题投票率最高的解决方案。

每个问题都有两个解决方案,用户可以对每个问题的一个解决方案进行投票。这是我目前的数据库。

+----------+------------+---------+
|    id    | id_problem |  vote   |
+----------+------------+---------+
|    1     |     1      |    25   |
|    2     |     1      |    10   |
|    3     |     2      |    18   |
|    4     |     2      |    2    |
|    5     |     3      |    6    |
|    6     |     3      |    7    |
|    7     |     4      |    11   |
|    8     |     4      |    4    |
|    9     |     5      |    5    |
|    10    |     5      |    2    |
+----------+------------+---------+

我希望得到这样的结果:(每个id_problem投票最高的行)

+----------+------------+---------+
|    id    | id_problem |  vote   |
+----------+------------+---------+
|    1     |     1      |    25   |
|    3     |     2      |    18   |
|    6     |     3      |    7    |
|    7     |     4      |    11   |
|    9     |     5      |    5    |
+----------+------------+---------+
SELECT 
    id, 
    id_problem, 
    max(vote) 
from 
    tablename
group by 
    id_problem 
order by 
    id_problem ASC

max(vote)决定了更大的投票,但它聚合了结果,然后你需要按id_problem分组,然后按asc排序。

您可以使用group by子句和max聚合函数来获得预期结果,例如:

select id, id_problem, max(vote) as vote
from result
group by id_problem
order by id_problem

下面是SQL Fiddle