码迷,mamicode.com
首页 > 数据库 > 详细

SQL多列查询最大值

时间:2018-08-28 12:10:44      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:rom   最大值   sql   查询   max   from   The   结果   center   

直接从某一列查询出最大值或最小值很容易,通过group by字句对合适的列进行聚合操作,再使用max()/min()聚合函数就可以求出。

样本数据如下:

key_id x y z
A 1 2 3
B 5 5 2
C 4 7 1
D 3 3 8

求查询每个key的最大值,展示结果如下:

key_id col
A 3
B 5
C 7
D 8

方案一:

对于列数不是很多的可以用case when语句,

select key_id,

       case when

            case when x > y then x else y end < z then z

            else case when x < y then y else x end

       end as gre

from sherry.greatests 

方案二:

如果有4列,5列可以先转为行数据再用聚合函数求,

select key_id, max(col) from

(select key_id, x as col from sherry.greatests

union all 

select key_id, y as col from sherry.greatests

union all

select key_id, z as col from sherry.greatests) as foo

group by key_id

SQL多列查询最大值

标签:rom   最大值   sql   查询   max   from   The   结果   center   

原文地址:https://www.cnblogs.com/xitingxie/p/9547300.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!