0

If I have two tables job, employee. I need to select all from job and append employee count for each job.

Supposed Result

job table
+-------------+-------------+
| id          | name        |
+-------------+-------------+
| 1           | Teacher     |
+-------------+-------------+
| 2           | Engineer    |
+-------------+-------------+
| 3           | Programmer  |
+-------------+-------------+

employee table
+-------------+-------------+-------------+
| id          | name        |   job_id    |
+-------------+-------------+-------------+
| 1           | employee N  |      1      |
+-------------+-------------+-------------+
| 2           | employee N  |      2      |
+-------------+-------------+-------------+
| 3           | employee N  |      3      |
+-------------+-------------+-------------+
| 4           | employee N  |      1      |
+-------------+-------------+-------------+
| 5           | employee N  |      3      |
+-------------+-------------+-------------+
| 6           | employee N  |      1      |
+-------------+-------------+-------------+

I need to select all from job and append employee count for each job.

Supposed Result

Result table
+-------------+-------------+--------------+
| id          | name        |employee count|
+-------------+-------------+--------------+
| 1           | Teacher     |      3       |
+-------------+-------------+--------------+
| 2           | Engineer    |      1       |
+-------------+-------------+--------------+
| 3           | Programmer  |      2       |
+-------------+-------------+--------------+

2 Answers 2

2

I like to use left join : )

SELECT job.id, job.name, count( * ) AS 'employee count'
FROM job
LEFT JOIN employee 
ON job.id = employee.job_id
GROUP BY job.id
Sign up to request clarification or add additional context in comments.

Comments

1

You want to use INNER JOIN to join the tables, then GROUP BY to group on the job id. Finally use COUNT() to get a count of each group

SELECT job.id, job.name, count(*) AS employee_count
FROM job
INNER JOIN employee 
  ON job.id = employee.job_id
GROUP BY job.id

You can see it live here http://sqlfiddle.com/#!2/9d59c1/1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.