0

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.

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. I tried sub selects too, with no luck. Anybody have any ideas?

1 Answer 1

6

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

Or you can use the PIVOT function:

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

Sign up to request clarification or add additional context in comments.

1 Comment

Very nice, thank you very much, the "case when" part is exactly what I was looking for, and very intuitive. Thanks for the help, and the PIVOT is incredibly useful as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.