选择最多两列的总和

时间:2010-02-17 00:25:23

标签: sql mysql

我有一个表比较。如果我跑

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行。

3 个答案:

答案 0 :(得分: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添加到查询中。

答案 1 :(得分:1)

如下:

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

答案 2 :(得分: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;