2011-10-13 40 views
2

我有以下要求:我們可以在SQL語句中使用SUM和Max函數嗎?

 
CODE   Marks 
A    50 
A    50 

B    60 
B    60 

C    20 
C    20 

現在,我想編寫一個查詢,顯示最佳射手的代碼和標記。在這個例子中它的B和120.如何在SQL中編寫它。

+1

能否請你澄清你的問題,並添加一些例如輸入/輸出?很難理解你在問什麼。另外,請指定您正在使用的數據庫。 – JohnFx

回答

3

標準SQL

SELECT 
    Code, MAX(SumMarks) 
FROM 
    (
    SELECT 
     SUM(Marks) as SumMarks, Code 
    FROM 
     SomeTable 
    GROUP BY 
     Code 
    ) foo 
GROUP BY 
    Code 

使用TOP或LIMIT(取消註釋如需要)。對於SQL Server,(WITH TIES使用),因爲你可能有得分的另一SUM具有相同的最大值,這是最好

SELECT -- TOP 1 -- WITH TIES if you have 2 scores the same 
    SUM(Marks) as SumMarks, Code 
FROM 
    SomeTable 
GROUP BY 
    Code 
ORDER BY 
    SUM(Marks) DESC 
-- LIMIT 1 

如果你不需要的東西,它應該激發你至少...

2

假設你想只含有最高總分的代碼的單個行,此查詢應該做的伎倆......(假設MS SQL)

SELECT TOP 1 Code, SCORE 
    FROM 
     (SELECT Code, SUM(Marks) as score FROM YourTable GROUP BY Code) 
    ORDER BY Score DESC 
1

的PostgreSQL或MySQL:

SELECT code 
    , marks 
    FROM (
    SELECT CODE 
      , sum(Marks) as marks 
     FROM yourtable 
    GROUP BY CODE 
    ORDER BY 2 DESC 
) mysums 
LIMIT 1 

SQL服務器:

SELECT TOP 1 
     code 
    , marks 
    FROM (
    SELECT CODE 
      , sum(Marks) as marks 
     FROM yourtable 
    GROUP BY CODE 
    ORDER BY 2 DESC 
) mysums 
相關問題