Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Join - Summing COUNT of Different Values

Tags:

sql

join

Let's say I have two tables orgs and states orgs is (o_ID, state_abbr) and states is (state_abbr, state)

o_ID     state_abbr
1        CT
2        OH
3        OH

state_abbr state
CT         Connecticut
OH         Ohio
Alabama    AL

I would like to create a view that shows the count of o_ID in each state:

state_abbr      state       count
CT              Connecticut 1
OH              Ohio        2

What kind of SQL Statement would I use? The ones that I have tried only show the first state and sum all the counts.

Thank you in advance.

like image 756
H Patel Avatar asked Mar 26 '26 10:03

H Patel


1 Answers

select
    o.state_abbr,
    s.state,
    o.[count]
from states s
inner join
(
    select state_abbr, count(*) as count
    from orgs
    group by state_abbr
) o
on s.state_abbr = o.state_abbr

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!