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;
Author by
Tripati Subudhi
Updated on June 04, 2022Comments
-
Tripati Subudhi almost 2 years
I have two tables. One is
Employee_Mstr
and other isEmployeeLeaveRequest_mstr
.My data:
-
Yusubov almost 12 yearslet us know what did you get, pick the answers please
-
-
Tripati Subudhi almost 12 yearsI 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 almost 12 yearsI 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 almost 12 yearsI updated the solution, with run results on MS SQL. At least it worked fine for me as you can see.
-
Shahbaz almost 12 years@CsabaBenko, why are you editing someone else's answer when you have your own answer to this question?!
-
Tripati Subudhi almost 12 yearsEven this one is also working but I cant mark your answer as only one we can mark as answer... Thanks for your response...
-
wroniasty almost 12 years@TripatiSubudhi sure, no problem. You can upvote it though ;)
-
Flashpix almost 12 yearsIf 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;