0

Given following table A

FlightID| Roles 1 | Pilot 1 | Steward 1 | Steward 2 | Pilot 2 | Co-Pilot 

How can I determine the number of stewards on each distinct flight? The output should be like this:

FlightID| Count 1 | 2 2 | 0 

First I tried:

select FlightID, count(Role) from A group by FlightID 

but this gives me the total number of roles per flight. Then I tried:

select FlightID, count(Role) from A where Role="Steward" group by FlightID 

this is partially right since it gives me the number of stewards per flight, but it does not take into account 0 stewards. How can I also include 0 stewards into the result?

2 Answers 2

3

You can use conditional aggregation.

select FlightID ,sum(case when Role = 'Steward' then 1 else 0 end) --or count(case when Role = 'Steward' then 1 end) from A group by FlightID 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. Do you see a way without using "case when .. then .. else .. end"?
2

Does your table really not have a primary key on it? If it does, this is a fairly easy LEFT JOIN:

SELECT a1.FlightId, COUNT(a2.FlightId) FROM A a1 LEFT JOIN A a2 ON a1.id = a2.id AND a2.Roles = 'Steward' GROUP BY a1.FlightId; 

http://ideone.com/BySBSx

1 Comment

Thanks, LEFT JOIN was the key.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.