rollup&&cube

group by 擴展 rollup&&cube

--按job分組計算不同job的匯總工資

  SELECT job, SUM (sal)
    FROM emp
GROUP BY job
ORDER BY job;

--向rollup傳遞一列

  SELECT job, SUM (sal)
    FROM emp
GROUP BY ROLLUP (job)
ORDER BY job;

image

--向rollup傳遞多列,根據job小計

  SELECT job, deptno, SUM (sal)
    FROM emp
GROUP BY ROLLUP (job, deptno)
ORDER BY job, deptno;

image

--修改傳遞給rollup的列的位置,根據部門小計

  SELECT deptno, job, SUM (sal)
    FROM emp
GROUP BY ROLLUP (deptno, job)
ORDER BY deptno, job;

image

--rollup與其它聚合函數使用,任何聚合函數都可以和rollup一起使用

  SELECT deptno, job, ROUND (AVG (sal), 2)
    FROM emp
GROUP BY ROLLUP (deptno, job)
ORDER BY deptno, job;

image

--使用cube子句

  SELECT deptno, job, SUM (sal)
    FROM emp
GROUP BY CUBE (deptno, job)
ORDER BY deptno, job;

image

--cube改變順序

  SELECT job, deptno, SUM (sal)
    FROM emp
GROUP BY CUBE (job, deptno)
ORDER BY job, deptno;

image

--grouping 返回0 1

  SELECT GROUPING (job), job, SUM (sal)
    FROM emp
GROUP BY ROLLUP (job)
ORDER BY job;

image

--轉換grouping返回值為有意義的值

  SELECT CASE GROUPING (job)
                   WHEN 1 THEN 'ALL JOBS'
                   ELSE job
              END AS job,
              SUM (sal)
    FROM emp
GROUP BY ROLLUP (job)
ORDER BY SUM (sal);

image

--grouping多列
  SELECT
  CASE GROUPING (deptno) WHEN 1 THEN  40 ELSE deptno END AS deptno,
  CASE GROUPING (job)      WHEN 1 THEN 'ALL JOBS'    ELSE job      END AS job,
         SUM (sal)
    FROM emp
GROUP BY ROLLUP (deptno,job)
ORDER BY deptno,job;

image


--cube與grouping一起使用
  SELECT
  CASE GROUPING (deptno) WHEN 1 THEN  40 ELSE deptno END AS deptno,
  CASE GROUPING (job)      WHEN 1 THEN 'ALL JOBS'    ELSE job      END AS job,
         SUM (sal)
    FROM emp
GROUP BY cube (deptno,job)
ORDER BY deptno,job;

image

--使用grouping sets只顯示小計結果
  SELECT deptno,job,
              SUM (sal)
    FROM emp
GROUP BY grouping sets (deptno,job)
ORDER BY deptno,job;

image

posted @ 2017-02-05 16:54  guilingyang  阅读(169)  评论(0编辑  收藏  举报