2015-10-14 25 views
1

我有以下查詢,顯示樞軸表:甲骨文案/替換支點分類結果

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 

等。

是否有可能以某種方式使用案例?

謝謝

+0

你嘗試'CASE WHEN總和(SAL)> 0 THEN 1 ELSE 0 END'? –

回答

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