R Saudlach
R Saudlach

Reputation: 388

SQL Join - Summing COUNT of Different Values

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.

Upvotes: 3

Views: 111

Answers (3)

user868322
user868322

Reputation: 5

SELECT O.STATE_ABBR,S.[STATE],COUNT(S.[STATE]) FROM ORGS O INNER JOIN STATES S ON O.STATE_ABBR = S.STATE_ABBR GROUP BY O.STATE_ABBR,S.[STATE]

Upvotes: 0

user596075
user596075

Reputation:

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

Upvotes: 3

RobO
RobO

Reputation: 41

You're looking for a "GROUP BY" statement, where you tell the database how to group your data for counting. You need to group by both "state_abbr" and "state", so your query would look like:

SELECT
    states.state_abbr
    , states.state
    , COUNT(*)
FROM
    orgs
    INNER JOIN states ON states.state_abbr=orgs.state_abbr
GROUP BY
    state_name

Upvotes: 1

Related Questions