Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL - Group By with Left Join

I have two tables. Table A has a list of employee names. Table B is a complex table with information about phone calls made by employees.

My goal is to make a table with columns 'name' and 'callCount'. I am aiming to do this with a 'left join' and a 'group by', but I keep missing the employees that have made no calls. How can I just get it to keep the name and just put a zero there?

Perhaps I am close and someone can point out my typo? Thanks in advance for your help, here is the SQL:

SELECT A.name, COUNT(B.call_id) AS 'outgoing call count' 
FROM EmployeeTable A 
LEFT JOIN CallTable B 
ON A.name = B.call_from_name
WHERE B.call_type LIKE 'outgoing' 
AND B.voice_mail = '0' 
...
GROUP BY A.name 
like image 687
Brandi Avatar asked Jul 12 '10 20:07

Brandi


People also ask

Can we use GROUP BY in left join?

MySQL LEFT JOIN with Group By ClauseThe Left Join can also be used with the GROUP BY clause. The following statement returns customer id, customer name, qualification, price, and date using the Left Join clause with the GROUP BY clause.

Can we use GROUP BY with join in SQL?

SQL Inner Join permits us to use Group by clause along with aggregate functions to group the result set by one or more columns. Group by works conventionally with Inner Join on the final result returned after joining two or more tables.

How join multiple tables with left join in SQL?

Syntax For Left Join:SELECT column names FROM table1 LEFT JOIN table2 ON table1. matching_column = table2. matching_column; Note: For example, if you have a left table with 10 rows, you are guaranteed to have at least 10 rows after applying join operation on two tables.

How do you do left join with the query in SQL?

LEFT JOIN SyntaxON table1.column_name = table2.column_name; Note: In some databases LEFT JOIN is called LEFT OUTER JOIN.


1 Answers

It's a JOIN not a NULL problem: your filter is changing the OUTER to an INNER JOIN. This means you only get COUNT where you have rows in CallTable (B) rather than the OUTER JOIN you wanted.

SELECT A.name, COUNT(B.call_id) AS 'outgoing call count' 
FROM
   EmployeeTable A 
   LEFT JOIN
   (
   SELECT call_from_name, call_id FROM CallTable
   WHERE call_type LIKE 'outgoing' 
     AND voice_mail = '0'
     AND /* other CallTable filters */
   ) B
   ON A.name = B.call_from_name
WHERE
     /* only EmployeeTable A filters */
GROUP BY A.name 

Edit: after your comment elsewhere, all your filters on B must be in the derived table, not in the outer where.

like image 139
gbn Avatar answered Oct 01 '22 19:10

gbn