앞선 쿼리에서 'EMPNO' 즉, 사원번호가 중복될 때,
동일한 사원번호를 가진 급여('SAL'칼럼)에 대한 정보가 중복되어 선택됨으로써 합산에 오차가 생겼다.
-> 'EMP' 테이블과 'EMP_BONUS' 테이블에 대해 JOIN을 수행하고, 이 과정에서 특정 조건에 의해 같은 사원의 정보가 중복되어 반환됨으로써 결과에 오차가 생겼다.
다음 쿼리는 합산하는 열에 중복되는 값이 있을 때 필요한 대체 해법이다.
이 원리의 쿼리는 모든 DBMS에서 작동한다.
select d.deptno, d.total_sal,
sum(e.sal * case when eb.type=1 then .1
when eb.type=2 then .2
else .3
end)
as total_bonus
from emp e,
emp_bonus eb,
(
# 부서값이 10인 행을 그룹화하여 합계를 구한 결과셋 반환
select deptno, sum(sal) as total_sal
from emp
where deptno = 10
group by deptno
) d
# 조건을 맞춰 'EMP' 테이블과 JOIN 실행
where e.deptno = d.deptno
and e.empno = eb.empno
group by d.deptno, d.total_sal;
>>
+--------+------------+--------------+
| deptno | totla_sal | total_bonus |
+--------+-------------+-------------+
| 10 | 8750 | 2135 |
+--------+-------------+-------------+