简体   繁体   English

Oracle 11G R2 SQL行到列

[英]Oracle 11G R2 SQL rows to columns

I have a table of bank staff information that looks like this: 我有一张银行职员信息表,看起来像这样:

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

I am actually done with this, but I completed the assignment using SQL common table expressions, and I can't use them in this project, I need them in this format. 我实际上已经完成了,但是我使用SQL公用表表达式完成了分配,但是我不能在该项目中使用它们,我需要这种格式的文件。

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

My issue is getting multiple columns with information from a row, I have this so far, 我的问题是从一行中获取多列包含信息的数据,到目前为止,

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

This outputs the correct information for numOfManagers, but making the next three columns eludes me without using CTE's. 这将为numOfManagers输出正确的信息,但是在不使用CTE的情况下使我难以理解的接下来的三列。 I tried sub selects too, with no luck. 我也尝试了子选择,没有运气。 Anybody have any ideas? 有人有什么想法吗?

You can use something like this: 您可以使用如下形式:

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

See SQL Fiddle with Demo 参见带有演示的SQL Fiddle

Or you can use the PIVOT function: 或者,您可以使用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;

See SQL Fiddle with Demo 参见带有演示的SQL Fiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM