SQL计算两个字段或者三个字段的最大值

        MAX是一个对单列数据进行操作,选择最大值,但是对于要选择同一行中两行值中较大一列,这样在sql中是没法使用的,考虑如下数据,要得到x,y中较大的一个

SQL中的MAX是不能直接使用的,但利用以下公式可以达到相应的目的, max(x,y)=(x+y+ABS(x-y))/2
ABS(x-y)是拿到x-y的差的绝对值,同样也可以得到如下公式: min(x,y)=(x+y-ABS(x-y))/2
因此可以得到相应的sql如下:

Sql代码 复制代码 收藏代码
  1. select id,x,y,(x+y+abs(x-y))/2 from xy; 
  select id,x,y,(x+y+abs(x-y))/2 from xy;

如果是要选择三个列中的最大值的话可以用max(x,max(y,z)),不过这样写出来的sql可是一大堆了:

考虑使用导出表,将三列数据合并到一列中来,然后再在外层Select中查出最大值,如以下脚本:

Sql代码 复制代码 收藏代码
  1. select id,MAX(m) from (  
  2.     select id,`x` as m from xyz   
  3.         unionall   
  4.     select id,`y` as m from xyz   
  5.         unionall   
  6.     select id,`z` as m from xyz  
  7. ) u groupby id; 
select id,MAX(m) from (
	select id,`x` as m from xyz 
		union all 
	select id,`y` as m from xyz 
		union all 
	select id,`z` as m from xyz
) u group by id;


引用http://qiang106.iteye.com/blog/693335
posted @ 2013-03-27 16:27  helloyu  阅读(3036)  评论(0)    收藏  举报