SQL左连接查询如何将左表重复的关联字段值设置为空
实现同员工仅第一条请假记录展示ID的SQL方案
现有数据表说明
- table1(员工表):存储员工基础信息,包含
EmployeeId、Employee Name两个字段,示例数据如下:
| EmployeeId | Employee Name |
|---|---|
| 1 | Employee1 |
| 2 | Employee2 |
- table2(请假记录表):存储员工请假记录,包含
EmployeeId、Leave Date两个字段,示例数据如下:
| EmployeeId | Leave Date |
|---|---|
| 1 | 01/08/2021 |
| 2 | 01/08/2021 |
| 1 | 02/08/2021 |
| 3 | 03/08/2021 |
| 1 | 04/08/2021 |
| 2 | 05/08/2021 |
原有问题修正
你提供的初始查询存在两处笔误:表名table 2存在非法空格,关联条件中table1.EmplaoyeeId拼写错误,可先修正后再参考以下方案实现需求。
具体实现方案
主流数据库通用方案(支持窗口函数场景)
通过ROW_NUMBER()窗口函数给同员工的请假记录按日期排序,仅第一条记录返回员工ID,其余行返回空值即可:
SELECT CASE WHEN row_num = 1 THEN t1.EmployeeId ELSE NULL END AS EmployeeId, t2.`Leave Date` AS LeaveDate FROM table1 t1 INNER JOIN ( SELECT EmployeeId, `Leave Date`, ROW_NUMBER() OVER(PARTITION BY EmployeeId ORDER BY `Leave Date` ASC) AS row_num FROM table2 ) t2 ON t1.EmployeeId = t2.EmployeeId ORDER BY t1.EmployeeId, t2.`Leave Date` ASC;
执行逻辑说明
- 子查询中按
EmployeeId分组,每组内按请假日期升序排序,为每条记录生成唯一行号 - 外层查询通过
CASE判断,仅行号为1的记录(即该员工第一条请假记录)展示员工ID,其余行对应位置为空 - 最终结果按员工ID、请假日期升序排序,符合常规展示需求
返回结果示例
| EmployeeId | LeaveDate |
|---|---|
| 1 | 01/08/2021 |
| NULL | 02/08/2021 |
| NULL | 04/08/2021 |
| 2 | 01/08/2021 |
| NULL | 05/08/2021 |
低版本数据库兼容方案(不支持窗口函数场景)
如果使用不支持窗口函数的低版本数据库(如MySQL 5.7及更早版本),可通过关联聚合子查询实现:
SELECT CASE WHEN t2.`Leave Date` = t_min.first_leave_date THEN t1.EmployeeId ELSE NULL END AS EmployeeId, t2.`Leave Date` AS LeaveDate FROM table1 t1 INNER JOIN table2 t2 ON t1.EmployeeId = t2.EmployeeId INNER JOIN ( SELECT EmployeeId, MIN(`Leave Date`) AS first_leave_date FROM table2 GROUP BY EmployeeId ) t_min ON t2.EmployeeId = t_min.EmployeeId ORDER BY t1.EmployeeId, t2.`Leave Date` ASC;
内容的提问来源于stack exchange,提问作者tarunhv1
相关产品推荐
相关产品推荐

