My Table structure & data-
CREATE TABLE EMPLOYEE
( EMP_ID NUMBER,
NAME VARCHAR2(100 BYTE),
SALARY NUMBER,
DEP_ID NUMBER,
ORG_ID NUMBER
);
insert into employee values (1, 'Mark', 6000, 44, 5);
insert into employee values (2, 'John', 4000, 46, 5);
insert into employee values (2, 'John', 4500, 2, 5);
insert into employee values (3, 'Terry', 5000, 44, 5);
insert into employee values (4, 'Carol', 15000, 48, 5);
insert into employee values (4, 'Carol', 15500, 4, 5);
insert into employee values (5, 'Lewis', 18000, 46, 5);
CREATE TABLE DEPARTMENT
( DEP_ID NUMBER,
DEP_NAME VARCHAR2(100 BYTE),
ORG_ID NUMBER
);
insert into DEPARTMENT values (null, 'NYD', 5);
insert into DEPARTMENT values (2, 'HR', 5);
insert into DEPARTMENT values (4, 'Analyst', 5);
In EMPLOYEE table, same employees can have 2 rows, one with a valid & other with an invalid DepartmentID. Other employees simply have one entry with an invalid DepartmentID.
I want to join EMPLOYEE & DEPARTMENT table in such a way that, if an EMPLOYEE has 2 rows, then only the row with a valid DepartmentID should be selected. If the EMPLOYEE has only 1 row with invalid DepartmentID, it should pick the default DEP_NAME (DEP_ID=null). Below is how the Query Output should look like-
| EMP_ID | NAME | SALARY | DEP_NAME |
|---------|-----------|--------|----------|
| 1 | Mark | 6000 | NYD |
| 2 | John | 4500 | HR |
| 3 | Terry | 5000 | NYD |
| 4 | Carol | 15500 | Analyst |
| 5 | Lewis | 18000 | NYD |
I tried different ways, but still unable to figure out. Please help
select
emp.EMP_ID, emp.NAME, emp.SALARY, dep.DEP_NAME
from
employee emp
join department dep on ....
where ....
Departments
? And why do you assume I downvoted on your question? Voting is anonymous.Dep_Id=null
. But I understand your point. The data that I have presented, it doesn't look really great.