自我推荐表. MySQL的

我有另一个问题.我似乎没有完全掌握这个概念.

我有一张桌子:

EMPLOYEES

| EMP_NO | APELLIDO | OFFICE | DIRECTOR | START_DATE | SALARY | COMMISSION | DEP_NO |

我必须获得OFFICE是’DIRECTOR'(简单,但……)的员工数据,我还必须包括一个列,该列将返回所有下属员工的全薪(工资佣金).

现在我知道我需要“复制”表格,以便能够让它自己引用(员工e1,员工e2等).但我正在努力获得那些下属的工资总额.

有什么想法吗?
(请帮忙)

编辑

对不起伙计们,真的.我的错.好的,这里有一些示例数据:

+--------+----------+------------+----------+------------+---------+----------+--------+
| EMP_NO | SURNAME  | OFFICE     | DIRECTOR | START_DATE | SALARY  |COMMISSION| DEP_NO |
+--------+----------+------------+----------+------------+---------+----------+--------+
|   7499 | ALONSO   |SALESPERSON |     7698 | 1981-02-23 | 1400.00 |   400.00 |     30 |
|   7521 | LOPEZ    | EMPLOYEE   |     7782 | 1981-05-08 | 1350.50 |     NULL |     10 |
|   7654 | MARTIN   |SALESPERSON |     7698 | 1981-09-28 | 1500.00 |  1600.00 |     30 |
|   7698 | GARRIDO  | DIRECTOR   |     7839 | 1981-05-01 | 3850.12 |     NULL |     30 |
|   7782 | MARTINEZ | DIRECTOR   |     7839 | 1981-06-09 | 2450.00 |     NULL |     10 |
|   7839 | REY      |    CEO     |     NULL | 1981-11-17 | 6000.00 |     NULL |     10 |
|   7844 | CALVO    |SALESPERSON |     7698 | 1981-09-08 | 1800.00 |     0.00 |     30 |
|   7876 | GIL      |  ANALIST   |     7782 | 1982-05-06 | 3350.00 |     NULL |     20 |
|   7900 | JIMENEZ  | EMPLOYEE   |     7782 | 1983-03-24 | 1400.00 |     NULL |     20 |
+--------+----------+------------+----------+------------+---------+----------+--------+

我现在需要做的是返回表格,其中包含员工GARRIDO和MARTINEZ(EMP_NO 7698和7782)的详细信息以及包含所有直属下属总薪水的附加栏目.像这样的东西:

+--------+----------+------------+----------+------------+---------+----------+--------+-----------+
| EMP_NO | SURNAME  | OFICIO     | DIRECTOR | FECHA_ALTA | SALARIO | COMISION | DEP_NO | TOTAL_EMP |
+--------+----------+------------+----------+------------+---------+----------+--------+-----------+    
|   7698 | GARRIDO  | DIRECTOR   |     7839 | 1981-05-01 | 3850.12 |     NULL |     30 |   6700    |
|   7782 | MARTINEZ | DIRECTOR   |     7839 | 1981-06-09 | 2450.00 |     NULL |     10 |  1350.50  |
+--------+----------+------------+----------+------------+---------+----------+--------+-----------+

最佳答案 我相信这应该做到.您只需要加入到您需要的其他行,然后分组就可以获得所需的总量.

SELECT
    D.emp_no,
    D.apellido,    -- Why is there one column named in Spanish and the rest in English?
    D.office,
    D.director,
    D.start_date,
    D.salary,
    D.commission,
    D.dep_no,
    SUM(COALESCE(S.salary, 0) + COALESCE(S.commission, 0)) AS subordinates_compensation
FROM
    Employees D
LEFT OUTER JOIN Employees S ON S.director = D.emp_no
WHERE
    D.office = 'Director'
GROUP BY
    D.emp_no,
    D.apellido,
    D.office,
    D.director,
    D.start_date,
    D.salary,
    D.commission,
    D.dep_no
点赞