1.ROLLUP服務器
ROLLUP的做用至關於
SQL> set autotrace on
SQL> select department_id,job_id,count(*)
2 from employees
3 group by department_id,job_id
4 union
5 select department_id,null,count(*)
6 from employees
7 group by department_id
8 union
9 select null,null,count(*)
10 from employees;函數
最後面的SA_REP表示此jobid沒有部門,爲null
這裏的union系統默認進行了排序性能
使用ROLLUP能達到上面GROUP BY的功能,但性能開銷更小
SQL> ed
已寫入 file afiedt.buf
1 select department_id,job_id,count(*)
2 from employees
3* group by rollup (department_id,job_id)
SQL> /spa
2.爲何ROLLUP會比GROUP BY性能好3d
ROLLUP(a,b,c)=a,b,c+a,b+a+All
經過一次全表掃描,得出a,b,c的分組統計信息後;分組統計a,b 相同,c不一樣的項便可獲得a,b;依此類推……,就不用去屢次全表掃描blog
3.ROLLUP的另類用法ROLLUP(a,(b,c))
ROLLUP((a,b))
SQL> ed
已寫入 file afiedt.buf排序
1 select department_id,job_id,count(*)
2 from employees
3* group by rollup ((department_id,job_id))
SQL> /
注意面的語句是group by rollup ((department_id,job_id))
不是group by rollup (department_id,job_id)io
4.GROUPING函數的做用是放總記file
如一個公司有多個部門,一個部門有多個崗位,一個崗位上有多我的
Rollup(部門,工做崗位) sum(每人的工資)
當部門的GROUPING爲0,工做崗位的GROUPING也爲0時,說明是公司發的總工資,此時放公司總計
當部門的GROUPING爲0,工做崗位的GROUPING也爲1時,說明是部門發的總工資,此時放部門小記
當部門的GROUPING爲1,工做崗位的GROUPING也爲1時,顯示的是某部門某職位的工資和計
SQL> SELECT department_id DEPTID, job_id JOB,
2 SUM(salary),
3 GROUPING(department_id) GRP_DEPT,
4 GROUPING(job_id) GRP_JOB
5 FROM employees
6 GROUP BY ROLLUP(department_id, job_id);select
第一個SA_REP表示此jobid沒有部門,爲null
5.GROUPING SETS與GROUPING的做用是不一樣的
Oracle服務器計算GROUPING SETS子句中全部的組並將結果經過UNION ALL組合成一個結果集.
GROUPING SETS的效果:1.只須要訪問一次基表.2.不須要寫很複雜的UNION語句.
SELECT department_id, job_id, null manager_id,avg(salary)
FROM employees
GROUP BY (department_id,job_id)
UNION ALL
SELECT null department_id, job_id, manager_id,avg(salary)
FROM employees
GROUP BY (job_id,manager_id)
等同於
SQL> set autotrace on
SQL> SELECT department_id, job_id,
2 manager_id,avg(salary)
3 FROM employees
4 GROUP BY GROUPING SETS ((department_id,job_id), (job_id,manager_id));
上面獲得的是經過job_id,manager_id分組的avg(salary)
下面的是經過department_id,job_id分組的avg(salary)