我正在尝试使用 SQL 选择一些信息,但没有成功。这就是我想要做的。
我有 2 张桌子:
具有以下列的表员工:
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
带列的表部门:
IDdepartment | name
1 | Thieves
2 | Madmen
我想选择每个部门的第一个和最后一个员工的姓氏和他们的员工人数。结果:
department_name | first_employee | last_employee | employee_count
Thieves | Smith | Anderson | 3
Madmen | Mason | Grumpy | 3
我能够通过以下查询获得第一位和最后一位员工的计数和 ID:
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;
但是,我找不到选择他们姓氏的正确方法。任何帮助将不胜感激。