假设在一个表中我有5列(a,b,c,d,e)每个都是一个整数值,这个表有100行,我们如何从每列的总和和列名中找到最大值sql?即max(sum(a),sum(b),sum(c),sum(d),sum(e))和columnname
答案 0 :(得分:1)
在许多数据库中,您可以使用greatest()
:
select greatest(sum(a), sum(b), sum(c), sum(d), sum(e))
from t;
在没有此功能的数据库中,您可以使用case
或取消忽略并重新聚合:
select sum(val)
from ((select a as val, 'a' as which from t) union all
(select b as val, 'b' as which from t) union all
(select c as val, 'c' as which from t) union all
(select d as val, 'd' as which from t) union all
(select e as val, 'e' as which from t)
) abcde
group by which
order by sum(val) desc
fetch first 1 row only;
这是ANSI语法。有些数据库使用TOP
或LIMIT
代替FETCH FIRST
。