在报表的开发当中,难免会遇到行转列的问题。
以Oracle中scott的emp为例,统计各职位的人员在各部门的人数分布情况,就可以用“行转列”:
scott的emp的原始数据为:
EMPNO
ENAME
JOB
MGR
HIREDATE
SAL
COMM
DEPTNO
7369
SMITH
CLERK
7902
12/17/1980
800.00
20
7499
ALLEN
SALESMAN
7698
2/20/1981
1600.00
300.00
30
7521
WARD
SALESMAN
7698
2/22/1981
1250.00
500.00
30
7566
JONES
MANAGER
7839
4/2/1981
2975.00
20
7654
MARTIN
SALESMAN
7698
9/28/1981
1250.00
1400.00
30
7698
BLAKE
MANAGER
7839
5/1/1981
2850.00
30
7782
CLARK
MANAGER
7839
6/9/1981
2450.00
10
7788
SCOTT
ANALYST
7566
4/19/1987
3000.00
20
7839
KING
PRESIDENT
11/17/1981
5000.00
10
7844
TURNER
SALESMAN
7698
9/8/1981
1500.00
0.00
30
7876
ADAMS
CLERK
7788
5/23/1987
1100.00
20
7900
JAMES
CLERK
7698
12/3/1981
950.00
30
7902
FORD
ANALYST
7566
12/3/1981
3000.00
20
7934
MILLER
CLERK
7782
1/23/1982
1300.00
10
使用“行转列”统计各职位的人员在各部门的分布人数后,数据为:
JOB
10(DEPTNO)
20(DEPTNO)
30(DEPTNO)
40(DEPTNO)
CLERK
1
2
1
0
SALESMAN
0
0
4
0
PRESIDENT
1
0
0
0
MANAGER
1
1
1
0
ANALYST
0
2
0
0
一、经典的实现方式
主要是利用decode函数、聚合函数(如max、sum等)、group by分组实现的
select t.job, count(decode(t.deptno, '10', 1)) as "10(DEPTNO)",
count(decode(t.deptno, '20', 1)) as "20(DEPTNO)",
count(decode(t.deptno, '30', 1)) as "30(DEPTNO)",
count(decode(t.deptno, '40', 1)) as "40(DEPTNO)"
from scott.emp t
group by t.job;
Classical Approach
二、PIVOT
Oracle 11g后,出现PIVOT,更简便地实现“行转列”。使用前,需确定数据库环境大于11g,最好也确认下生产环境的数据库是否大于11g,避免项目后期出现状况。
with tmp_tab as(
select t.job, t.deptno
from scott.emp t
)
select * from tmp_tab t pivot(count(1) for deptno in (10, 20, 30, 40));
PIVOT
三、PIVOT XML
使用经典的方法和PIVOT方法,DEPTNO的参数是硬编码的。而通过PIVOT XML能解决这一问题,使分列条件可以是动态的。但,输出的是XML的CLOB的格式。目前,Java读取PIVOT XML CLOB貌似比较困难(本人没有成功读取,可见下文描述,如有知晓者,请知悉)。
with tmp_tab as(
select t.job, t.deptno
from scott.emp t
)
select * from tmp_tab t pivot xml (count(1) for deptno in (select deptno from scott.dept));
PIVOT XML
然而,当写完上面PIVOT XML滴时候,使用Java读取数据时,却发现读取不了PIVOT XML的CLOB(普通的并且数据相同的CLOB却能正常读取)
努力了几天,亦尝试下载目前最新的OJDBC,但仍然报错。
报错为
“Invalid column type: getCLOB not implemented for class oracle.jdbc.driver.T4CNamedTypeAccessor”–ojdbc6.jar
https://www.cnblogs.com/nick-huang/tag/Java/default.html