0

I have three tables: states (id, name); hospitals (id, name, level_id, state_id); level (id, name). The table (level) shows the quality of each hospital. A States can have several hospitals that have different quality of service (level). I want to achieve a MySQL query like below

Tables :

level

id| name    |  
1 | level 1 |  
2 | level 2 | 
3 | level 3 |

hospitals

id| name | level_id | state_id  
1 | Hos A| 1        | 22  
2 | Hos B| 3        | 7   
3 | Hos C| 2        | 13  
...

result:

states | level 1 | level 2| level 3 | total
state 1| 0       | 1      | 1       | 2
state 2| 3       | 4      | 7       | 14  
...

I have tried something along this line but just got stuck. Any help will be appreciated

SELECT state.name states, hos.level_id 'level 1', hos.level_id 'level 2', hos.level_id 'level 3'
FROM state

LEFT JOIN hospital hos ON hos.state_id = state.id

ORDER BY state.name
1
  • Consider handling issues of data display in application code Commented Apr 21, 2020 at 19:24

1 Answer 1

1

Is this what you want?

select state,
       sum(level_id = 1) as num_1,
       sum(level_id = 2) as num_2,
       sum(level_id = 3) as num_3,
       count(*) as total
from hospitals h
group by state;
Sign up to request clarification or add additional context in comments.

3 Comments

Isn't there suppose to be a join somewhere?
@Lekia . . . A JOIN doesn't seem necessary.
Thanks, @Gordon Linoff I just made a little tweak to it and got it working.

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.