程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> Oracle數據庫 >> Oracle教程 >> Oracle簡單的列轉行

Oracle簡單的列轉行

編輯:Oracle教程

Oracle簡單的列轉行


需求是,統計每個部門不同工種的薪水總和。

SQL> select deptno,ename,job,sal from emp;
DEPTNO ENAME JOB SAL
---------- ---------- --------- ----------
20 SMITH CLERK 800
30 ALLEN SALESMAN 1600
30 WARD SALESMAN 1250
20 JONES MANAGER 2975
30 MARTIN SALESMAN 1250
30 BLAKE MANAGER 2850
10 CLARK MANAGER 2450
20 SCOTT ANALYST 3000
10 KING PRESIDENT 5000
30 TURNER SALESMAN 1500
20 ADAMS CLERK 1100
30 JAMES CLERK 950
20 FORD ANALYST 3000
10 MILLER CLERK 1300
已選擇14行。

SQL> select deptno,
nvl(sum(decode(job, 'MANAGER', sal)), 0) "s_MANAGER",
nvl(sum(decode(job, 'ANALYST', sal)), 0) "s_ANALYST",
nvl(sum(decode(job, 'CLERK', sal)), 0) "s_CLERK",
nvl(sum(decode(job, 'PRESIDENT', sal)), 0) "s_PRESIDENT",
nvl(sum(decode(job, 'SALESMAN', sal)), 0) "s_SALESMAN"
from emp
group by deptno;
DEPTNO s_MANAGER s_ANALYST s_CLERK s_PRESIDENT s_SALESMAN
---------- ---------- ---------- ---------- ----------- ----------
30 2850 0 950 0 5600
20 2975 6000 1900 0 0
10 2450 0 1300 5000 0

SQL> select deptno,
nvl(sum(case job when 'MANAGER' then sal else null end), 0) "s_MANAGER",
nvl(sum(case job when 'ANALYST' then sal else null end), 0) "s_ANALYST",
nvl(sum(case job when 'CLERK' then sal else null end), 0) "s_CLERK",
nvl(sum(case job when 'PRESIDENT' then sal else null end), 0) "s_PRESIDENT",
nvl(sum(case job when 'SALESMAN' then sal else null end), 0) "s_SALESMAN"
from emp
group by deptno;

DEPTNO s_MANAGER s_ANALYST s_CLERK s_PRESIDENT s_SALESMAN
---------- ---------- ---------- ---------- ----------- ----------
30 2850 0 950 0 5600
20 2975 6000 1900 0 0
10 2450 0 1300 5000 0

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved