通过添加重复项来删除重复项[SQL]

时间:2018-10-06 14:47:58

标签: sql oracle group-by

我有这样的查询:

select employee_id, salary
from salary
left join employee on salary.employee_id=employee.id_employee;

它向我返回这些结果

EMPLOYEE ID  | SALARY
-------------|-------
1            |     50
2            |     50
3            |     50
1            |     30

如何通过添加重复项来删除重复项,如下所示:

EMPLOYEE ID |  SALARY
------------|--------
1           |      80
2           |      50
3           |      50

3 个答案:

答案 0 :(得分:2)

没有理由将left joinsalaryemployee。大概employee_id中的每个salary都是有效的雇员。所以,这应该做您想要的:

select s.employee_id, sum(s.salary) as salary
from salary s
group by s.employee_id;

如果您要所有名员工,即使不是salary表中的员工,那么外部联接也是合适的,但是employee应该是第一位:

select e.id_employee, sum(s.salary) as salary
from employee e left join
     salary s
     on s.employee_id = e.id_employee
group by e.id_employee;

不在salary中的员工的值为NULL

请注意,此查询中的group by条件位于employee first 表的left join上。

答案 1 :(得分:1)

select employee_id, SUM(salary) as salary
from salary
left join employee on salary.employee_id=employee.id_employee
group by emplyee_id;

答案 2 :(得分:0)

这正是group by子句的用途。您必须group by emplopyee_id并指定要如何汇总工资:

SELECT   employee_id, SUM(salary)
FROM     salary
GROUP BY employee_id