
select deptno, sum(sal)
from emp
group by deptno;
select job, sum(sal)
from emp
group by job;
-- 에러 발생
select job, sum(sal)
from emp
where sum(sal) >=5000
group by job;
ORA-00934: 그룹 함수는 허가되지 않습니다
https://docs.oracle.com/error-help/db/ora-00934/00934. 00000 - "group function is not allowed here"
*Cause: One of the group functions, such as AVG, COUNT, MAX,
MIN, SUM, STDDEV, or VARIANCE, was used in a WHERE or GROUP BY
clause.
*Action: Remove the group function from the WHERE or GROUP BY
clause. The desired result may be achieved by including the
function in a subquery or HAVING clause.
3행, 8열에서 오류 발생
💡
where절에 그룹함수로 검색조건을 줄 수 X
having절 사용해야함
📌 having절은 별칭 사용할 수 Xselect job, sum(sal) from emp group by job having sum(sal) >= 5000;
💡 HAVING절은 집계 함수의 조건을 걸기 위해 사용하는 필터
GROUP BY로 묶인 그룹 결과에 조건을 적용할 때 사용
💡 select문의 6가지 절
5 select 검색할 컬럼명
1 from 테이블명
2 where 검색조건
3 group by 그룹핑할 컬럼명
4 having 그룹함수를 사용한 검색조건
6 order by 정렬할 컬럼명
from - where - group by - having - select - order by문제. 아래의 SQL문에 대해서 실행 순서를 올바르게 나열한 것은?
SELECT DEPTNO, COUNT(EMPNO)
FROM SCOTT.EMP
WHERE SAL >= 400
GROUP BY DEPTNO
HAVING COUNT(EMPNO) >= 3
ORDER BY DEPTNO;
① FROM → WHERE → GROUP BY → HAVING → ORDER BY → SELECT
② FROM → WHERE → HAVING → GROUP BY → ORDER BY → SELECT
③ FROM → WHERE → GROUP BY → SELECT → HAVING → ORDER BY
④ FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY
답: ④
select deptno, min(sal)
from emp
group by deptno
having min(sal) >= 1000;
select job, sum(sal)
from emp
where job != 'SALESMAN'
group by job
having sum(sal) >= 3000
order by sum(sal) desc;
💡
where job != 'SALESMAN'--> 일반 조건
having sum(sal) >= 3000--> 그룹함수 검색 조건
.
다음과 같이 실행을 해도 실행은 되나 성능이 느림
그래서 반드시 그룹함수를 사용하지 않은 검색조건은 WHERE절 이용하기
select job, sum(sal)
from emp
group by job
having sum(sal) >= 3000 and job !='SALESMAN'
order by sum(sal) desc;
select deptno, sum(sal)
from emp
where deptno != 20
group by deptno
having sum(sal) >= 700
order by sum(sal) desc;