选择两列之和的最大值

3

我有一个比较表。如果我运行

SELECT comparisonID,stu1Vers,stu2Vers,stu1,stu2 
    from comparisons 
    WHERE stu1!=stu2 and assignmentid=9;

我得到的东西大致是这样的:
+--------------+----------+----------+------+------+
| comparisonID | stu1Vers | stu2Vers | stu1 | stu2 |
+--------------+----------+----------+------+------+
|          287 |       12 |        2 |    1 |    6 |
|          286 |       12 |        1 |    1 |    6 |
|          276 |       11 |        2 |    1 |    6 |
|          275 |       11 |        1 |    1 |    6 |
|          266 |       10 |        2 |    1 |    6 |
|          265 |       10 |        1 |    1 |    6 |
|          257 |        9 |        2 |    1 |    6 |
|          256 |        9 |        1 |    1 |    6 |
...
|          391 |       19 |        1 |    1 |    6 |
|          392 |       19 |        2 |    1 |    6 |
+--------------+----------+----------+------+------+

我希望选择整行数据,其中stu1Vers+stu2Vers的值最大。我一直试图使用以下方式:
select c.comparisonid,c.stu1vers,c.stu2vers,max(totvers) 
from comparisons as c join 
    (select comparisonid, stu1vers+stu2vers as totvers 
    from comparisons where stu1!=stu2 group by comparisonid) as cm 
on c.comparisonid = cm.comparisonid and c.stu1vers+c.stu2vers = cm.totvers;

但是它返回的东西相当随机:
+--------------+----------+----------+--------------+
| comparisonid | stu1vers | stu2vers | max(totvers) |
+--------------+----------+----------+--------------+
|          220 |        1 |        1 |           21 |
+--------------+----------+----------+--------------+

我想获取第一个表格中的第392行。


如果有多行具有相同的最大值,应该发生什么?返回所有行还是只返回一行?如果是后者,那么应该返回哪一行? - Mark Byers
实际上,表中还有另外两列,分别是stu1和stu2的id。因此,返回所有这些列,但按照stu1或stu2进行分组。对于任何学生的任何作业,max(stu1vers+stu2vers)都保证是唯一的。 - Kyle Schmidt
3个回答

3

如果你想要在多行具有相同的最大值时获取所有这些行,那么可以使用以下查询:

SELECT * FROM Table1
WHERE stu1Vers + stu2Vers = (SELECT MAX(stu1Vers + stu2Vers) FROM Table1)

包括您的条件:
SELECT * FROM Table1
WHERE stu1Vers + stu2Vers = (
    SELECT MAX(stu1Vers + stu2Vers)
    FROM Table1
    WHERE stu1!=stu2 and assignmentid=9
) AND stu1!=stu2 and assignmentid=9

结果:

392, 19, 2, 1, 6

关于您对问题的更新,我不确定您是想要按stu1和stu2分组返回所有行。也许您是希望按这些列排序?如果是这样,请在查询中添加ORDER BY stu1, stu2


2
如何尝试以下内容:

类似这样的东西如何:

SELECT TOP 1 comparisonid, stu1vers, stu2vers, stu1Vers + stu2Vers AS MaxValue
  FROM comparisons
 ORDER BY MaxValue DESC

请注意:此处仅返回一个匹配项,而非问题更新中要求的所有匹配项。 - Mark Byers
1
“TOP 1” 不是在 MySQL 中返回一行的方法。 - Mark Byers

0

你尝试过类似这样的东西吗?

 SELECT comparisonID,stu1Vers,stu2Vers,stu1,stu2, max(stu1Vers + stu2Vers) as maximum
     from comparisons 
     WHERE stu1!=stu2 and assignmentid=9 order by maximum desc limit 1;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接