2010-02-17 135 views
2

我有一個表比較。如果我運行選擇兩列總和的最大值

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。

+0

如果存在具有相同最大值的多行,會發生什麼?全部退回,還是隻有一個?如果後者是哪一個? –

+0

表中實際上還有兩列,分別是stu1和stu2的id。所以歸還所有這些,但由stu1或stu2分組)。對於任何學生任何作業,max(stu1vers + stu2vers)保證是唯一的。 –

回答

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 

關於您對問題的更新,我不確定您的意思是什麼,以返回所有t他按stu1和stu2分組。也許你的意思是按這些欄目排序?如果是這樣,請將ORDER BY stu1, stu2添加到查詢中。

1

如何像:

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

注意:這隻會返回其中一個匹配項,而不是所有匹配項,如問題更新中所要求的那樣。 –

+1

而'TOP 1'並不是你如何在MySQL中返回一行。 –

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;