Oracle 11G R2 SQL行到列

tru*_*ype 0 sql oracle pivot oracle11gr2

我有一张银行职员信息表,如下所示:

branchNumber    Position    firstName    lastName    staffNumber
------------    --------    ---------    --------    -----------
25              Manager     john         doe         11111
25              Secretary   robert       paulson     11112
25              Secretary   cindy        lu          11113
66              Manager     tim          timson      22223
66              Manager     jacob        jacobson    22224
66              Secretary   henry        henryson    22225
66              Supervisor  paul         paulerton   22226
Run Code Online (Sandbox Code Playgroud)

我实际上完成了这个,但我使用SQL公用表表达式完成了赋值,我不能在这个项目中使用它们,我需要它们以这种格式.

branchNumber    numOfManagers    numOfSecretaries    numOfSupervisors    totalEmployees
------------    -------------    ----------------    ----------------    --------------
25                    1                 2                   0                   3
66                    2                 1                   1                   4
Run Code Online (Sandbox Code Playgroud)

我的问题是从一行获取多列信息,到目前为止,我有这个,

SELECT branchNumber, COUNT(*) AS numOfManagers
FROM Staff
WHERE position = 'Manager'
GROUP BY branchNumber, Position;
Run Code Online (Sandbox Code Playgroud)

这会为numOfManagers输出正确的信息,但是在不使用CTE的情况下使接下来的三列无法使用.我也尝试过子选择,没有运气.有人有什么想法吗?

Tar*_*ryn 6

你可以使用这样的东西:

select branchnumber,
  sum(case when Position ='Manager' then 1 else 0 end) numofManagers,
  sum(case when Position ='Secretary' then 1 else 0 end) numofSecretaries,
  sum(case when Position ='Supervisor' then 1 else 0 end) numofSupervisors,
  count(*) totalEmployees
from yourtable
group by branchnumber
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo

或者你可以使用这个PIVOT功能:

select branchnumber,
  'Manager', 'Secretary', 'Supervisor',
  TotalEmployees
from
(
  select t1.branchnumber,
    t1.position,
    t2.TotalEmployees
  from yourtable t1
  inner join
  (
    select branchnumber, count(*) TotalEmployees
    from yourtable
    group by branchnumber
  ) t2
    on t1.branchnumber = t2.branchnumber
) x
pivot
(
  count(position)
  for position in ('Manager', 'Secretary', 'Supervisor')
) p;
Run Code Online (Sandbox Code Playgroud)

请参阅SQL Fiddle with Demo