2015-10-14 3 views
1

Я следующий запрос для отображения повернута таблицы:Oracle случай/заменить стержень группирования результат

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

Пробовали ли вы 'случай, когда сумма (сал)> 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 
Смежные вопросы