2025-05-23

Java代碼 
GROUPING  
GROUPING函數可以接受一列,返回0或者1。如果列值為空,那麼GROUPING()返回1;如果列值非空,那麼返回0。GROUPING隻能在使用ROLLUP或CUBE的查詢中使用。當需要在返回空值的地方顯示某個值時,GROUPING()就非常有用。  
 
1、在ROLLUP中對單列使用GROUPING()  
 
SQL> select pision_id,sum(salary)  
  2  from employees2  
  3  group by rollup(pision_id)  
  4  order by pision_id;  
 
DIV SUM(SALARY)  
— ———–  
BUS     1610000 
OPE     1320000 
SAL     4936000 
SUP     1015000 
        8881000 
 
加上GROUPING來看看  
 
SQL> select grouping(pision_id),pision_id,sum(salary)  
  2  from employees2  
  3  group by rollup(pision_id)  
  4  order by pision_id;  
 
GROUPING(DIVISION_ID) DIV SUM(SALARY)  
——————— — ———–  
                    0 BUS     1610000 
                    0 OPE     1320000 
                    0 SAL     4936000 
                    0 SUP     1015000 
                    1         8881000 
可以看到,為空的地方返回1,非空的地方返回0。  
 
2、使用CASE轉換GROUPING()的返回值  
 
可能你會覺得前面的0和1太枯燥瞭,代表不瞭任何意義,說白瞭就是不夠人性化,呵呵。這個時候我們可以使用CASE來轉換為一些有意義的值。  
 
SQL> select  
  2  case grouping(pision_id)  
  3  when 1 then all pisions 
  4  else pision_id  
  5  end as p,  
  6  sum(salary)  
  7  from employees2  
  8  group by rollup(pision_id)  
  9  order by pision_id;  
 
DIV           SUM(SALARY)  
————- ———–  
BUS               1610000 
OPE               1320000 
SAL               4936000 
SUP               1015000 
all pisions     8881000 
 
3、使用CASE和GROUPING()轉換多個列的值  
 
SQL> select  
  2  case grouping(pision_id)  
  3  when 1 then all pisions 
  4  else pision_id  
  5  end as p,  
  6  case grouping(job_id)  
  7  when 1 then all jobs 
  8  else job_id  
  9  end as job,  
 10  sum(salary)  
 11  from employees2  
 12  group by rollup(pision_id,job_id)  
 13  order by pision_id,job_id;  
 
DIV           JOB      SUM(SALARY)  
————- ——– ———–  
BUS           MGR           530000 
BUS           PRE           800000 
BUS           WOR           280000 
BUS           all jobs     1610000 
OPE           ENG           245000 
OPE           MGR           805000 
OPE           WOR           270000 
OPE           all jobs     1320000 
SAL           MGR          4446000 
SAL           WOR           490000 
SAL           all jobs     4936000 
 
DIV           JOB      SUM(SALARY)  
————- ——– ———–  
SUP           MGR           465000 
SUP           TEC           115000 
SUP           WOR           435000 
SUP           all jobs     1015000 
all pisions all jobs     8881000 
 
16 rows selected.  
 
4、CUBE與GROUPING()結合使用  
 
SQL> select  
  2  case grouping(pision_id)  
  3  when 1 then all pisions 
  4  else pision_id  
  5  end as p,  
  6  case grouping(job_id)  
  7  when 1 then all jobs 
  8  else job_id  
  9  end as job,  
 10  sum(salary)  
 11  from employees2  
 12  group by cube(pision_id,job_id)  
 13  order by pision_id,job_id;  
 
DIV           JOB      SUM(SALARY)  
————- ——– ———–  
BUS           MGR           530000 
BUS           PRE           800000 
BUS           WOR      &nbsp

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *