SQL计算两个字段或者三个字段的最⼤值
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;
引⽤
发布评论