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如下:
- 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中查出最大值,如以下脚本:
- select id,MAX(m) from (
- select id,`x` as m from xyz
- unionall
- select id,`y` as m from xyz
- unionall
- select id,`z` as m from xyz
- ) 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


浙公网安备 33010602011771号