I’m trying to select some information using SQL, but with no success. Here’s what I’m trying to do.
I have 2 tables:
Table employees with following columns:
IDemployee | name | surname | department_id
1 | John | Smith | 1
2 | Jane | Smith | 1
3 | Neo | Anderson | 1
4 | John | Mason | 2
5 | James | Cameron | 2
6 | Morpheus| Grumpy | 2
Table departments with columns:
IDdepartment | name
1 | Thieves
2 | Madmen
I want to select surnames of first and last employees of every department and count of their employees.
Result:
department_name | first_employee | last_employee | employee_count
Thieves | Smith | Anderson | 3
Madmen | Mason | Grumpy | 3
I was able to get count and ID’s of first and last employees with following query:
SELECT d.IDdepartment, COUNT(*) as "employee_count", MIN(e.IDemployee) as "first_employee", MAX(e.IDemployee) as "last_employee"
FROM ( employees e INNER JOIN departments d ON d.IDdepartment=e.department_id)
GROUP BY d.name;
However, I can’t find the right way to select their surnames. Any help would be greatly appreciated.
While there might be another way, one way is to use your query as a subquery:
And here is the fiddle: http://sqlfiddle.com/#!2/17a5b/2
Good luck.