原创MySQL同时取出最大值和最小值所在整行
Posted HuaBro
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了原创MySQL同时取出最大值和最小值所在整行相关的知识,希望对你有一定的参考价值。
老规矩;直接上群友问题
这是原求助者的答案
下面放我的方法
为了说明这个问题:
先创建一张表,并插入数据
CREATE TABLE overtime ( employee_name VARCHAR(50) NOT NULL, department VARCHAR(50) NOT NULL, hours INT NOT NULL, PRIMARY KEY (employee_name , department) ); INSERT INTO overtime(employee_name, department, hours) VALUES(\'Diane Murphy\',\'Accounting\',37), (\'Mary Patterson\',\'Accounting\',74), (\'Jeff Firrelli\',\'Accounting\',40), (\'William Patterson\',\'Finance\',58), (\'Gerard Bondur\',\'Finance\',47), (\'Anthony Bow\',\'Finance\',66), (\'Leslie Jennings\',\'IT\',90), (\'Leslie Thompson\',\'IT\',88), (\'Julie Firrelli\',\'Sales\',81), (\'Steve Patterson\',\'Sales\',29), (\'Foon Yue Tseng\',\'Sales\',65), (\'George Vanauf\',\'Marketing\',89), (\'Loui Bondur\',\'Marketing\',49), (\'Gerard Hernandez\',\'Marketing\',66), (\'Pamela Castillo\',\'SCM\',96), (\'Larry Bott\',\'SCM\',100), (\'Barry Jones\',\'SCM\',65);
**Schema (mysql v8.0)**
| employee_name | department | hours |
| ----------------- | ---------- | ----- |
| Anthony Bow | Finance | 66 |
| Barry Jones | SCM | 65 |
| Diane Murphy | Accounting | 37 |
| Foon Yue Tseng | Sales | 65 |
| George Vanauf | Marketing | 89 |
| Gerard Bondur | Finance | 47 |
| Gerard Hernandez | Marketing | 66 |
| Jeff Firrelli | Accounting | 40 |
| Julie Firrelli | Sales | 81 |
| Larry Bott | SCM | 100 |
| Leslie Jennings | IT | 90 |
| Leslie Thompson | IT | 88 |
| Loui Bondur | Marketing | 49 |
| Mary Patterson | Accounting | 74 |
| Pamela Castillo | SCM | 96 |
| Steve Patterson | Sales | 29 |
| William Patterson | Finance | 58 |
---
下面是查询sql
with t1 as (SELECT 1 as id, hours min_hours, FIRST_VALUE(employee_name) OVER ( ORDER BY hours ) least_emp FROM overtime limit 1), t2 as (SELECT 1 as id, hours max_hours, FIRST_VALUE(employee_name) OVER ( ORDER BY hours desc ) first_emp FROM overtime limit 1) select t1.min_hours,t1.least_emp,t2.max_hours,t2.first_emp from t1 ,t2 where t1.id=t2.id ;
具体代码查看本人创建的
https://www.db-fiddle.com/f/91TmSU9SwVwFBqCTHPPyh8/1
https://www.db-fiddle.com/f/91TmSU9SwVwFBqCTHPPyh8/18
函数介绍
【特别说明】转载请注明,原创不易,请勿用作商业用途。
以上是关于原创MySQL同时取出最大值和最小值所在整行的主要内容,如果未能解决你的问题,请参考以下文章
第 258 场周赛(5867. 反转单词前缀/ 5868. 可互换矩形的组数 / 5869. 两个回文子序列长度的最大乘积(状态压缩) / 5870. 每棵子树内缺失的最小基因值(小大合并))(代码片