I have three tables and I would like to make a query of getting all companies. BUT I would like to know the amount of active employees by getting the last record per person from the people_history table and matching it with the company they work for.
Table: people
—————————————————————————————————————————————————
id | name | ssn | phone |
—————————————————————————————————————————————————
1 | John | 9591 | 12341234 |
2 | Jane | 1049 | 12340987 |
—————————————————————————————————————————————————
Table: people_history
—————————————————————————————————————————————————
id | person_id | company_id | time |
—————————————————————————————————————————————————
1 | 1 | 5 | stamp |
2 | 1 | 7 | stamp |
3 | 2 | 2 | stamp |
4 | 1 | 2 | stamp |
—————————————————————————————————————————————————
Table: companies
————————————————
id | name |
————————————————
1 | Name 1 |
2 | Name 2 |
… |
————————————————
By doing the following I don't look for the last record per person.
SELECT c.name AS company_name, COUNT(h.id) AS employees
FROM companies c
LEFT JOIN people_history h ON h.id = c.company_id
GROUP BY c.id
Any suggestions?
Thank you!
Not tested but shut work:
SELECT c.name AS company_name, COUNT(h.id) AS employees
FROM companies c
LEFT JOIN (SELECT *
FROM people_history ph1
WHERE id = (SELECT MAX(id)
FROM people_history ph2
WHERE ph1.person_id = ph2.person_id)
) h ON h.id = c.company_id
GROUP BY c.id
This is easily solved with an anti-join:
SELECT c.name AS company_name, COUNT(h1.id) AS employees
FROM companies c
LEFT JOIN people_history h1 ON h1.id = c.company_id
LEFT JOIN people_history h2 ON h2.id = c.company_id AND h2.person_id = h1.person_id AND h2.id > h1.id
WHERE h2.id IS NULL
GROUP BY c.id
This counts only the last record (highest id) for each person in the person_history table.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.