如何用UNION+EXISTS单查询从两差异表取单表数据?
合并薪资覆盖表与标准薪资表的查询实现
我们有两张结构存在差异的薪资表,仅生效起止日期字段通用:
employee_salary_override(薪资覆盖表):存储员工的个性化薪资配置employee_standard_salary(标准薪资表):存储对应岗位的标准薪资数据
需要通过单个SQL查询实现:优先从薪资覆盖表获取符合条件的记录;若覆盖表无对应记录,再从标准薪资表提取数据,以此替代原本的两个独立查询,同时保证查询性能不受影响。
以下是实现该逻辑的SQL示例:
-- 从薪资覆盖表获取指定员工的生效薪资记录 select override_salary_num as overrideSalaryNumber, -- 覆盖薪资编号 effective_start_dte as effectiveStartDate, -- 生效起始日期 effective_end_dte as effectiveEndDate, -- 生效结束日期 employee_Id as employeeId, -- 员工ID null as employeeRole, -- 岗位编号(覆盖表无此字段,设为null) null as employeeRoleType, -- 岗位类型(覆盖表无此字段,设为null) bonus_rate as bonusRate, -- 奖金比例 base_salary as baseSalary, -- 基本工资 merit_increase_Rate as meritRate -- 绩效涨幅比例 from employee_salary_override a WHERE a.employee_Id in (1) -- 指定目标员工ID and a.effective_start_dte <= '2023-12-01' -- 记录生效起始日期不晚于指定日期 and a.effective_end_dte >= '2023-12-01' -- 记录生效结束日期不早于指定日期 UNION -- 当覆盖表无对应员工的生效薪资记录时,从标准薪资表获取指定岗位的生效薪资记录 select standard_salary_num as standardSalaryNumber, -- 标准薪资编号 effective_start_dte as effectiveStartDate, -- 生效起始日期 effective_end_dte as effectiveEndDate, -- 生效结束日期 null as employeeId, -- 员工ID(标准表无此字段,设为null) b.employee_Role_Number as employeeRole, -- 岗位编号 1 as employeeRoleType, -- 岗位类型(固定值1) bonus_rate as bonusRate, -- 奖金比例 base_salary as baseSalary, -- 基本工资 merit_increase_Rate as meritRate -- 绩效涨幅比例 from employee_standard_salary b where b.employee_Role_Number=5 -- 指定目标岗位编号 AND b.effective_start_dte <= '2023-12-01' -- 记录生效起始日期不晚于指定日期 AND b.effective_end_dte >= '2023-12-01' -- 记录生效结束日期不早于指定日期 -- 判断指定员工是否无生效的覆盖薪资记录 AND NOT EXISTS ( select * from employee_salary_override c where c.employee_Id in (1) and c.effective_start_dte <= '2023-12-01' and c.effective_end_dte >= '2023-12-01' );
说明:原示例SQL的
NOT EXISTS子查询中存在表别名引用错误,已修正为使用子查询自身的表别名c,确保逻辑正确性。
内容的提问来源于stack exchange,提问作者Codeip
相关产品推荐
相关产品推荐

