group by, having
■ group by
select distinct topic from help;
select topic from help group by topic;
ex) 부서별 급여 합계
select department_id, sum(salary)
from EMPLOYEES
group by department_id;
* 사용불가 : 단일그룹의 그룹 함수가 아닙니다.
select distinct departmet_id, sum(salary)
from EMPLOYEES;
부서별 사원수와 평균 급여
select department_id, sum(salary), count(salary), avg(salary)
from employees
group by department_id;
부서별 직급별 사원수와 평균 급여
select department_id, job_id, sum(salary), count(salary), avg(salary)
from employees
group by department_id, job_id
order by department_id, job_id;
: group by 여러개 가능
select department_id, job_id,
to_char(sum(salary), '999,999') as '총급여',
to_char(avg(salary), '999,999') as '평균급여'
from employees
group by department_id, job_id
order by department_id, job_id;
: 보기좋게 출력
■ having
현재 부서별 사원수
select department_id, count(*)
from employees
where department_id is not null
group by department_id
having count(*) >= 10;
: 그룹함수는 where절에서 사용불가 따라서 having 절에서 조건
■ rollup
그룹별 합계 정보를 추가해서 보여주는 함수
ROLLUP구문은 GROUP BY 절과 같이 사용 되며, GROUP BY절에 의해서 그룹 지어진 집합 결과에 대해서 좀 더 상세한 정보를 반환하는 기능을 수행 한다.
SELECT절에 ROLLUP을 사용함으로써 보통의 SELECT된 데이터와 그 데이터의 총계를 구할 수 있다.
select l.CITY, d.DEPARTMENT_NAME, e.JOB_ID, count(*) , sum(e.salary) from EMPLOYEES e, DEPARTMENTS d,LOCATIONS l where e.department_id = d.department_id and d.LOCATION_ID = l.LOCATION_ID group by rollup(l.city, d.department_name, e.job_id) order by l.city, d.department_name, e.job_id;