2017-07-05 30 views
-1

假设在一个表中我有5列(a,b,c,d,e)每个整数值,并且这个表有100行,我们如何才能找到最大值(a),sum(b),sum(c),sum(d),sum(e))和列名在SQL如何从列中找到最大值

+2

用您正在使用的数据库标记您的问题。 –

+1

请分享你的工作,你试图解决什么问题?阅读“https://stackoverflow.com/help/how-to-ask” –

+0

戈登的答案一如既往! – davejal

回答

1

在许多数据库中,您可以使用greatest()

select greatest(sum(a), sum(b), sum(c), sum(d), sum(e)) 
from t; 

在数据库中没有此功能,您可以使用case或逆转置和reaggregate:

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