简体   繁体   中英

Joining two tables SQL

I have a question. I have two tables employees and salary and I want to display the full name and salary grade of all employee who's grade_ID is 2 or 3 sort by employee_ID.

Here are the tables:

Salary_ID      LOW_SALARY       High Salary
1                1              250000
2                250001         500000
3                500001         750000
4                750001         999999

EMPLOYEE_ID     FIRST_NAME     Last_NAME   Salary
1               James          Smith       800000
22               Roy           Red         375000
2                Ron           Johnson     550000
5                Rob           Green       225000

I know I have to join the tables, this is what I have so far:

QUERY

SELECT employees2.FIRST_NAME,
       employees2.last_name,
       salary_grades.SALARY_GRADE_ID,
       employees2.SALARY
FROM employees2,
     salary_grades
ORDER BY employees2.EMPLOYEE_ID;

what do i do next? I am stuck. Can anyone help me out? Thank you.

It may be the query you're looking for:

SELECT E.EMPLOYEE_ID
    ,E.FIRST_NAME
    ,E.LAST_NAME
    ,E.SALARY
FROM employees E
INNER JOIN salary S ON S.LOW_SALARY <= E.SALARY
                      AND S.HIGH_SALARY >= E.SALARY
                      AND S.SALARY_ID IN (2,3)
ORDER BY E.EMPLOYEE_ID

Hope this will help you.

Simply have to use a join condition that compares the employee salary with the low and high limits of the salary rank, ie

SELECT E.*, S.* FROM Employee AS E
INNER JOIN dbo.Salary AS S 
ON S.LOW_SALARY <= E.Salary AND S.High_Salary >= E.Salary

If you want, you can filter by Salary_Id between 2 and 3

NOTE: This syntax should work in the 3 types of servers.

Test data, for SQL Server:

CREATE TABLE Salary (Salary_Id INT, LOW_SALARY INT, High_Salary INT)
INSERT INTO Salary VALUES(1,1,250000)
INSERT INTO Salary VALUES(2,250001,500000)
INSERT INTO Salary VALUES(3,500001,750000)
INSERT INTO Salary VALUES(4,750001,999999)

CREATE TABLE Employee (Employee_Id INT, FIRST_NAME varchar(50), Last_NAME varchar(50), Salary INT)
INSERT INTO Employee VALUES(1, 'James', 'Smith', 800000)

I'll give the SQL Server (2008+) answer.

SELECT E.FIRST_NAME, E.last_name, S.SALARY_GRADE_ID, E.SALARY
FROM employees2 E
JOIN salary_grades S  ON (E.SALARY BETWEEN S.LOW_SALARY AND S.HIGH_SALARY) AND S.SALARY_ID IN (2, 3)
ORDER BY  E.EMPLOYEE_ID;
SELECT employees2.FIRST_NAME, employees2.LAST_NAME, employees2.SALARY, salary_grades.SALARY_GRADE_ID
FROM  employees2, salary_grades
WHERE employees2.SALARY BETWEEN salary_grades.LOW_SALARY AND salary_grades.HIGH_SALARY 
ORDER BY salary_grades.SALARY_GRADE_ID

So I tried using this script, it works but do i use IN to display the range of 2 and 3 in sqldeveloper?

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