ROLLUP - Information & Database Systems

advertisement
CSED421
Database Systems Lab
Extended Group By Queries
Group function

GROUP BY



Find the job and average salary of each jobs


Sort the data with distinct value for data of specified columns
Limit the window of data processed by the aggregate function
Select job, avg(salary)
from DevelopTeam
group by job;
If you also want to determine the average salary over all jobs, you must
run an additional query.
Extended Group

Cause extra rows to be added to the summary output


ROLLUP
CUBE
ROLLUP

WITH ROLLUP



Execute additional implicit GROUP BY queries with columns, which is
specified in GROUP BY clauses
Produce group summaries from right to left and a total summary
SQL Example


SELECT
FROM
GROUP
WITH ROLLUP;
SELECT
FROM EMP;
job,
BY
AVG(sal)
EMP
job
AVG(sal)
ROLLUP

If “n” is the number of columns listed in the GROUP BY clause, there will
be n+1 levels of summaries.

Group by Continent, Country, City with ROLLUP




(Continent, Country, City)
(Continent, Country)
(Continent)
()
ROLLUP for Multiple Columns

Results depends on a sequence of
columns in GROUP BY clauses.
SELECT deptno, job, AVG(sal)
FROM EMP
GROUP BY deptno, job
WITH ROLLUP;
≠
SELECT job, deptno, AVG(sal)
FROM EMP
GROUP BY job, deptno
WITH ROLLUP;
ROLLUP with Conditions

Specify some conditions for ROLLUP
SELECT deptno, job, AVG(sal)
FROM EMP
GROUP BY deptno, job
WITH ROLLUP
HAVING AVG(sal) > 2000;
CUBE

WITH CUBE

Generate summaries for all combinations of the columns specified in GROUP
BY clauses

If “n” is the number of columns listed in the GROUP BY clause, there will
be 2 n summary combinations.

GROUP BY A, B, C with CUBE




(A, B, C)
(A, B), (A, C), (B, C)
(A), (B), (C), (D)
()
CUBE

MySQL doesn’t yet support CUBE.
SELECT deptno, job, AVG(sal)
FROM EMP
GROUP BY deptno, job
WITH CUBE;
SELECT deptno, job, AVG(sal)
FROM EMP
GROUP BY deptno, job
WITH ROLLUP
UNION
SELECT deptno, job, AVG(sal)
FROM EMP
GROUP BY job, deptno
With ROLLUP;
Practice


EMP table
EMPNO
NUMBER(4)
직번
ENAME
VARCHAR2(10)
이름
JOB
VARCHAR2(9)
직위
MGR_EMPNO
NUMBER(4)
상사 직번
HIREDATE
DATE
고용일
SAL
NUMBER(7, 2)
급여
COMM
NUMBER(7, 2)
추가 급여
DEPTNO
NUMBER(2)
부서번호
DEPTNO
NUMBER(2)
부서번호
DNAME
VARCHAR2(14)
부서명
LOC
VARCHAR2(13)
부서위치
DEPT table
Practice

Source lab6.sql
http://ids.postech.ac.kr/dblab2014/lab6.sql
Practice
1.
부서명(DNAME) 및 직위(JOB)별 급여(SAL)의 합을 다음과 같이 출
력하시오.


급여의 내림차순으로 정렬
MySQL에서 ROLLUP과 ORDER
BY는 동시에 사용할 수 없으므
로
subquery를 사용하여 해결
Practice
2.
부서명(DNAME) 및 직위(JOB)별 급여(SAL)의 합을 다음과 같이 출
력하시오.


급여의 내림차순으로 정렬
급여의 합이 2000이상인 부서 및
직위 그룹을 출력 (Use cube)
Practice
3.
관리자가 있는 사람들에 대해서 각 부서(DEPTNO) 별 직위(JOB)별
로 직원수를 다음과 같은 형태로 출력하시오.

부서(DEPTNO), 직위(JOB)
순으로 정렬
Practice
4.
관리자의 이름과 관리자가 관리하는 사원들의 직위별 급여 합, 직
원 수, 평균 급여를 다음과 같이 출력하시오.

관리자의 이름은 중복이 없다
고
가정
Download