0

I need help. I am trying to get the salary and taxable allowances of an employee from the 2 tables, one holds the employee salary and the other his allowance.

The 2 tables share a common column that is the EmpID.

My code only returns a result for the employees that have a taxable allowance.

This is what I have tried:

select  
    Employee.EmpID, amount as Allw, bSalary 
from 
    Employee  
left join
    EmployeeAllowance on (Employee.EmpID = EmployeeAllowance.EmpID)  
where 
    taxStatus = 1 
    and Employee.EmpID = 'PC899'
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Ms_YMG
  • 15
  • 1

1 Answers1

2

Without seeing your tables, my guess is that the problem is with your taxStatus = 1 in your WHERE statement. This will drop records where the EmployeeAllowance table doesn't have an entry for the employee. You can change your query to only pull taxStatus=1 records from your EmployeeAllowance table BEFORE left joining it in:

SELECT Employee.EmpID,
    amount AS Allw,
    bSalary
FROM Employee
LEFT JOIN EmployeeAllowance ON 
    Employee.EmpID = EmployeeAllowance.EmpID AND
    employeeAllowance.taxStatus = 1
WHERE Employee.EmpID = 'PC899'

This is equivalent to doing a subquery to restrict that table before joining like:

SELECT Employee.EmpID,
    amount AS Allw,
    bSalary
FROM Employee
LEFT JOIN (SELECT * FROM EmployeeAllowance WHERE taxStatus = 1) as ea ON 
    Employee.EmpID = ea.EmpID 
WHERE Employee.EmpID = 'PC899'

It's just the first one is a little less verbose.

JNevill
  • 46,980
  • 4
  • 38
  • 63