sql中两个和的最大总和

时间:2013-07-04 08:28:10

标签: sql sql-server-2005

我有桌子:

Bonus     Value

500       1400

1500       177

1800       453

1200       100

800       2500

200         50

780        740

我想打印列的总和,以最大值为准。

我试过以下:

select 
case when sum(bonus)>sum(Value) then sum(bonus) end
case when sum(Value)>sum(bonus) then sum(Value) end
from emp

但我没有得到结果。

错误:

Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'case'.

3 个答案:

答案 0 :(得分:5)

您的语法不正确,CASE关键字只出现一次:

select 
  case when sum(bonus)>sum(Value) then sum(bonus)
     else sum(Value) 
  end as MaxSum
from emp

答案 1 :(得分:3)

您的case声明有误,请尝试以下方法:

select case when sum(bonus)>sum(Value) then sum(bonus) else sum(Value) end
from emp

答案 2 :(得分:1)

另一种方式:

SELECT TOP (1) *
FROM
  ( SELECT SUM(Bonus) AS MaxSum, 'Bonus' AS SummedColumn FROM emp
    UNION
    SELECT SUM(Value), 'Value' FROM emp
  ) AS tmp
ORDER BY MaxSum DESC ;

SQL-Fiddle

进行测试