我有这样的查询:
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
答案 0 :(得分:2)
没有理由将left join
从salary
到employee
。大概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