3

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.

3 Answers 3

3
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
Sign up to request clarification or add additional context in comments.

2 Comments

worked as soon as i removed the []'s; guess mySQL doesn't like square brackets. Thanks!!
@HPatel I'm sorry, I assumed you were using SQL Server (don't know why I thought that). I've modified my post to reflect.
1

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

Comments

0

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]

Comments

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.