How to get all rows from left table in a join statement?

13,768

Solution 1

SELECT tab1.emp_cd, tab1.emp_name, SUM(tab2.num_dy)
FROM Employee_Mstr tab1, "2nd Table Records" tab2
where tab1.emp_cd = tab2.emp_cd
group by tab1.emp_cd, tab1.emp_name;

Should work, just set the correct table name for the 2nd table.

Solution 2

Use GROUP BY.

select t1.emp_cd, t1.emp_name, sum(t2.num_dy) from 
  Employee_Mstr t1 left join 
  EmployeeLeaveRequest_mstr t2 on t1.emp_cd = t2.emp_cd group by t1.emp_cd, t2.emp_name;
Share:
13,768
Tripati Subudhi
Author by

Tripati Subudhi

Updated on June 04, 2022

Comments

  • Tripati Subudhi
    Tripati Subudhi almost 2 years

    I have two tables. One is Employee_Mstr and other is EmployeeLeaveRequest_mstr.

    My data:

    My data

    • Yusubov
      Yusubov almost 12 years
      let us know what did you get, pick the answers please
  • Tripati Subudhi
    Tripati Subudhi almost 12 years
    I tried this but this is giving me only Emp_cd 3 records but not 1 and 2 as I need all from left table.
  • Tripati Subudhi
    Tripati Subudhi almost 12 years
    I tried this but this is giving me only Emp_cd "3" records but not 1 and 2 as I need all records from left table.
  • Csaba Benko
    Csaba Benko almost 12 years
    I updated the solution, with run results on MS SQL. At least it worked fine for me as you can see.
  • Shahbaz
    Shahbaz almost 12 years
    @CsabaBenko, why are you editing someone else's answer when you have your own answer to this question?!
  • Tripati Subudhi
    Tripati Subudhi almost 12 years
    Even this one is also working but I cant mark your answer as only one we can mark as answer... Thanks for your response...
  • wroniasty
    wroniasty almost 12 years
    @TripatiSubudhi sure, no problem. You can upvote it though ;)
  • Flashpix
    Flashpix almost 12 years
    If you need all results from the left table we need a left join. SELECT tab1.emp_cd, tab1.emp_name, SUM(tab2.num_dy) FROM Employee_Mstr tab1 LEFT JOIN "2nd Table Records" tab2 ON tab1.emp_cd = tab2.emp_cd group by tab1.emp_cd, tab1.emp_name;