自我推荐表。 MySQL的

时间:2016-05-27 13:57:19

标签: mysql sql database

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

我有一张桌子:

EMPLOYEES

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

我必须获取员工的数据,他们的办公室是“董事”。 (简单,但......)我还必须包括一个列,它将返回所有下属员工的全薪(工资+佣金)。

现在我知道我需要复制'这个表让我能够自己参考(员工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  |
+--------+----------+------------+----------+------------+---------+----------+--------+-----------+

1 个答案:

答案 0 :(得分:2)

我相信这应该做到。您只需要JOIN到您需要的其他行,然后分组即可获得所需的总金额。

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