首页 > 代码库 > rollup&&cube

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;

技术分享

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

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

技术分享

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

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

技术分享

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

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

技术分享

--使用cube子句

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

技术分享

--cube改變順序

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

技术分享

--grouping 返回0 1

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

技术分享

--轉換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);

技术分享

--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;

技术分享


--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;

技术分享

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

技术分享

rollup&&cube