SQL - 如何为每个部门获取具有MIN和MAX id的特定列?

时间:2013-02-06 19:15:59

标签: sql

我正在尝试使用SQL选择一些信息,但没有成功。这就是我想要做的。

我有两张桌子:

表格员工包含以下列:

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;

然而,我找不到正确的方法来选择他们的姓氏。任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:0)

这是基于现有Oracle表的一般Oracle示例。如果在您的SQL版本中可用,则需要使用分析函数。您没有指定要使用的SQL。如果您的SQL中有FIRST()和LAST()解析f-ns,那么这应该可行:

SELECT empno, deptno, sal,
   MIN(sal) KEEP (DENSE_RANK FIRST ORDER BY sal) OVER (PARTITION BY deptno) "Lowest",
   MAX(sal) KEEP (DENSE_RANK LAST ORDER BY sal) OVER (PARTITION BY deptno) "Highest"
 FROM scott.emp
ORDER BY deptno, sal
/

See lowest and highest salary by dept in output of above query:

DEPTNO  SAL     Lowest  Highest
---------------------------------
10      1300    1300    5000
10      2450    1300    5000
10      5000    1300    5000
20      800     800     3000
20      1100    800     3000
20      2975    800     3000
....

答案 1 :(得分:0)

虽然可能有另一种方法,但一种方法是将查询用作子查询:

SELECT d.name department_name, 
  e.surname first_employee,
  e2.surname last_employee,
  t.employee_count
FROM (
    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
  ) t JOIN employees e on t.first_employee = e.IDemployee
  JOIN employees e2 on t.last_employee = e2.IDemployee
  JOIN departments d on t.IDdepartment = d.IDdepartment

这是小提琴:http://sqlfiddle.com/#!2/17a5b/2

祝你好运。