Oracle 11G R2 SQL行到列

时间:2012-09-28 19:41:19

标签: 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

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

branchNumber    numOfManagers    numOfSecretaries    numOfSupervisors    totalEmployees
------------    -------------    ----------------    ----------------    --------------
25                    1                 2                   0                   3
66                    2                 1                   1                   4

我的问题是从一行获取包含信息的多个列,到目前为止我已经这样了,

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

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

1 个答案:

答案 0 :(得分: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

请参阅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;

请参阅SQL Fiddle with Demo