2012-09-28 81 views
0

我有銀行的工作人員信息的表,看起來像這樣:的Oracle 11g R2 SQL行列

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的。我也嘗試了子選擇,沒有運氣。任何人有任何想法?

回答

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

+0

非常好,非常感謝你很多時候,「情況下」部分正是我所看到的爲,並且非常直觀。感謝您的幫助,而且PIVOT也非常有用。 – trueCamelType