I need some help with conditions on left join, my query is as follows
declare @emp table (id int, name varchar(100))
insert into @emp values (1,'Emp1')
insert into @emp values (2,'Emp2')
insert into @emp values (3,'Emp3')
insert into @emp values (4,'Emp4')
insert into @emp values (5,'Emp5')
--selecT * from @emp
declare @salary table(salaryid int, empid int, salary decimal(10,2))
insert into @Salary values (3,3,10000)
insert into @Salary values (4,4,15000)
insert into @Salary values (3,5,10000)
declare @oldsalary table(oldsalaryid int, empid int, oldsalary decimal(10,2))
insert into @oldsalary values (1,1,20000)
insert into @oldsalary values (2,2,25000)
--select * from @Salary
--select * from @oldsalary
declare @rating table (salaryid int, rating varchar(10))
insert into @rating values (4, 'D')
insert into @rating values (3, 'C')
insert into @rating values (1, 'B')
insert into @rating values (2, 'A')
--select * from @rating
select e.id, e.name, isnull(os.oldsalary, s.salary) salary, r.rating from @emp e
left join @salary s on e.id=s.empid
left join @oldsalary os on e.id=os.empid
left join @Rating r on r.salaryid = isnull(os.oldsalaryid, s.salaryid)
and this is the output
id name salary rating
1 Emp1 20000 B
2 Emp2 25000 A
3 Emp3 10000 C
4 Emp4 15000 D
5 Emp5 10000 C
As you can see from the query, if oldsalaryid is null then salaryid is used to join the rating table. So the left join is completely based on the value of the column. Is this the proper approach, by looking at the data everything seems to be showing correctly. Can I use this query?