0

我正在尝试使用 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;

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

4

2 回答 2

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

祝你好运。

于 2013-02-06T19:31:15.790 回答
0

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

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
....
于 2013-02-06T19:26:21.777 回答