如何计算PIVOT查询中的所有级别?

时间:2013-08-01 13:24:34

标签: sql oracle pivot

如何计算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'));

1 个答案:

答案 0 :(得分:1)

要包含所有作业而不在IN的{​​{1}}子句中明确列出它们,除了动态sql之外,您可以使用PIVOT并按如下方式重写查询:

PIVOT XML

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)
 )

但是,要获得数据的友好表示,您必须明确提取值:

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  ;

SQLFiddle Demo