Oracle Group By 用法之 —— Cube

cube子句在dw环境用的比较多,特别是在产生交叉报表的情况,演示一个cube的例子


  SQL 10G>create table test(sales varchar2(10),dest varchar2(10),revenue number);
  Table created.
  SQL 10G>insert into test values('smith','hangzhou',1000);
  1 row created.
  SQL 10G>insert into test values('smith','wenzhou',2000);
  1 row created.
  SQL 10G>insert into test values('allen','wenzhou',3000);
  1 row created.
  SQL 10G>insert into test values('allen','wenzhou',4000);
  1 row created.
  SQL 10G>commit;
  Commit complete.
  
  SQL 10G>select * from test;
  SALES   DEST     REVENUE
  ---------- ---------- ----------
  smith   hangzhou     1000
  smith   wenzhou     2000
  allen   wenzhou     3000
  allen   wenzhou     4000
  
  比如说我们想统计每个sales的总销售收入,每个sales在各个城市的销售收入,另外还想知道每个城市所有sales的销售收入总额,以及所有sales的总收入
  
  就像以下报表

-----------------------------------------------------------------
        hangzhou wenzhou
  allen          7000   7000
  smith    1000    2000   3000
        1000    9000   10000

------------------------------------------------------------------
  
  
  那我们运行下面这条语句就行了
  SQL 10G>select sales,dest,sum(revenue) from test group by cube(sales,dest);
  SALES   DEST    SUM(REVENUE)
  ----------     ----------        ------------
                10000                   所有sales的总销售收入
         wenzhou  9000                 所有sales在温州的销售收入
         hangzhou  1000                 所有sales在杭州的销售收入
  allen             7000                  allen的所有销售收入
  allen    wenzhou   7000                   allen在温州的销售收入
  smith           3000                   smith所有的销售收入
  smith   wenzhou   2000                    smith在温州的销售收入
  smith   hangzhou  1000                    smith在杭州的销售收入
  8 rows selected.
  
  如果不想统计城市这个维度,那么用rollup子句
  
        hangzhou wenzhou
  allen                   7000     7000
  smith    1000   2000   3000
                    10000
  
  SQL 10G>select sales,dest,sum(revenue) from test group by rollup(sales,dest);
  SALES   DEST    SUM(REVENUE)
  ---------- ---------- ------------
  allen   wenzhou    7000 allen在温州的销售收入
  allen            7000 allen的所有销售收入
  smith   wenzhou    2000 smith在温州的销售收入
  smith   hangzhou    1000  smith在杭州的销售收入
  smith           3000 smith所有的销售收入
                10000 所有sales的总销售收入
  6 rows selected.

你可能感兴趣的:(oracle,sql,table,报表)