【原創】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 

 函數介紹

 

【特別說明】轉載請注明,原創不易,請勿用作商業用途。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM