我有以下查询来显示数据透视表:
select deptno, clerk, salesman,
manager, analyst, president
from (select deptno, job, sal
from emp )
pivot( sum(sal) for job in
( 'CLERK' as clerk,
'SALESMAN' as salesman,
'MANAGER' as manager,
'ANALYST' as analyst,
'PRESIDENT' as president ) )
order by deptno
/
结果:
DEPTNO CLERK SALESMAN MANAGER ANALYST PRESIDENT
---------- ------- -------- ------- ------- ---------
10 1300 0 2450 0 6000
20 1900 0 2975 6000 0
30 950 5600 2850 0 0
但是现在我必须确定我们有价值设置 - 它将任意数字替换为1(当设置工资时),所以我将
DEPTNO CLERK SALESMAN MANAGER ANALYST PRESIDENT
---------- ------- -------- ------- ------- ---------
10 1 0 1 0 1
ETC。
是否有可能以某种方式使用案例?
谢谢
答案 0 :(得分:3)
您可以在子查询中执行此操作:
select deptno, clerk, salesman, manager, analyst, president
from (select deptno, job,
max(case when sal > 0 then 1 else 0 end) as salflag
from emp )
pivot( max(salflag) for job in
('CLERK' as clerk,
'SALESMAN' as salesman,
'MANAGER' as manager,
'ANALYST' as analyst,
'PRESIDENT' as president )
)
order by deptno;
我还认为条件聚合方法非常简单:
select deptno,
max(case when job = 'CLERK' and sal > 0 then 1 else 0 end) as clerk,
max(case when job = 'SALESMAN' and sal > 0 then 1 else 0 end) as salesman,
max(case when job = 'MANAGER' and sal > 0 then 1 else 0 end) as manager,
max(case when job = 'ANALYST' and sal > 0 then 1 else 0 end) as analyst,
max(case when job = 'PRESIDENT' and sal > 0 then 1 else 0 end) as president
from emp
group by deptno;
答案 1 :(得分:2)
这是在pivot
完成后执行此操作的一种方法。
with pvt as (select deptno, clerk, salesman,
manager, analyst, president
from (select deptno, job, sal
from emp )
pivot( sum(sal) for job in
( 'CLERK' as clerk,
'SALESMAN' as salesman,
'MANAGER' as manager,
'ANALYST' as analyst,
'PRESIDENT' as president ) )
order by deptno)
select deptno,
case when clerk > 0 then 1 else 0 end as clerk,
case when salesman > 0 then 1 else 0 end as salesman,
case when manager > 0 then 1 else 0 end as manager,
case when analyst > 0 then 1 else 0 end as analyst,
case when president > 0 then 1 else 0 end as president
from pvt