如何计算 PIVOT 查询中所有级别的计数?例如,这包括 ename 和 job,但如何计算所有工作级别的计数,而不仅仅是 CLERK、SALESMAN 和 MANAGER?
with pivot_data as (
select ename, job
from scott.emp
)
select * from pivot_data
pivot (count(*) for job in('CLERK', 'SALESMAN', 'MANAGER'));
IN
要包含所有作业而不在 的子句中明确列出它们PIVOT
,除了动态 sql 之外,您可以使用PIVOT XML
和重写查询,如下所示:
-- sample of data
with t1(col) as(
select 'CLERK' from dual union all
select 'SALESMAN' from dual union all
select 'MANAGER' from dual
)
select col_xml
from t1
pivot xml(
count(*) for col in(select col from t1)
)
XML 结果:
COL_XML
--------------------------------------------------------------------------------
<PivotSet><item><column name = "COL">CLERK</column><column name = "COUNT(*)">1</
column></item><item><column name = "COL">MANAGER</column><column name = "COUNT(*
)">1</column></item><item><column name = "COL">SALESMAN</column><column name = "
COUNT(*)">1</column></item></PivotSet>
但是,为了获得数据的友好表示,您必须显式提取值:
SQL> with t1(col) as(
2 select 'CLERK' from dual union all
3 select 'SALESMAN' from dual union all
4 select 'MANAGER' from dual
5 )
6 select extractvalue(col_xml,'/PivotSet/item[1]/column[2]') col_1
7 , extractvalue(col_xml,'/PivotSet/item[2]/column[2]') col_2
8 , extractvalue(col_xml,'/PivotSet/item[3]/column[2]') col_3
9 from ( select col_xml
10 from t1
11 pivot xml(
12 count(*) for col in(select col from t1)
13 )
14 )
15 ;
结果:
COL_1 COL_2 COL_3
-----------------
1 1 1