简体   繁体   中英

SQL query to join two tables without common column in oracle DB

I have 2 tables employee and job_role as below. I need to write a SQL query to find designation of each employee by joining this table.

Input Table

Employee

e_id    e_name  Salary
-----------------------
1       ABC     1000
2       CDE     2000
3       GHI     3500
4       JKL     5000
5       MNO     4000
6       XYZ     3000

Job_role

Designation   Sal_min   Sal_max
-------------------------------
Associate      1000      2000
Lead           2001      3000
Manager        3001      5000

Problem: if salary from employee table is in the range sal_min to sal_max , find the designation

Desired output:

e_id    e_name  Salary  Designation
-----------------------------------    
 1      ABC     1000    Associate
 2      CDE     2000    Associate
 3      GHI     3500    Manager
 4      JKL     5000    Manager
 5      MNO     4000    Manager
 6      XYZ     3000    Lead

The ON clause can consist of other operations than = . Here you can use <= and >= (or BETWEEN if you like).

SELECT E.E_ID,
       E.E_NAME,
       JR.DESIGNATION
       FROM EMPLOYEE E
            LEFT JOIN JOB_ROLE JR
                      ON JR.SAL_MIN <= E.SALARY
                         AND JR.SAL_MAX >= E.SALARY;

(Note: I used LEFT JOIN for the case that there are any employees where the salary doesn't match. I guessed you rather want to see them with a NULL designation than not at all.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM