简体   繁体   中英

max sum of two sums in sql

I have table:

Bonus     Value

500       1400

1500       177

1800       453

1200       100

800       2500

200         50

780        740

I wanted to print the sum of column whichever is maximum.

I Tried Following:

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

But i had not got the result.

Error:

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

Your syntax is incorrect, CASE keyword goes only once:

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

Your case statement is wrong, try this one:

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

Another way:

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 ;

Test at SQL-Fiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM