在sql中如何从列中找到max

时间:2017-07-05 22:30:12

标签: sql

假设在一个表中我有5列(a,b,c,d,e)每个都是一个整数值,这个表有100行,我们如何从每列的总和和列名中找到最大值sql?即max(sum(a),sum(b),sum(c),sum(d),sum(e))和columnname

1 个答案:

答案 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语法。有些数据库使用TOPLIMIT代替FETCH FIRST