SQL多列查询最大值
生活随笔
收集整理的這篇文章主要介紹了
SQL多列查询最大值
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
直接從某一列查詢出最大值或最小值很容易,通過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
轉載于:https://www.cnblogs.com/xitingxie/p/9547300.html
總結
以上是生活随笔為你收集整理的SQL多列查询最大值的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 65个面试常见问题技巧回答,你知道吗
- 下一篇: mysql使用IS NULL查询null