我有桌子:
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'.
答案 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 ;
进行测试