Count by area type query (1 Viewer)

bigal.nz

Registered User.
Local time
Today, 23:20
Joined
Jul 10, 2016
Messages
92
Hello,

I want to create a query to sum by state - the data doesn't have state, it has city (in this data there is only a few cities per state).

So I presume I need a table to Map city to state?

The data looks like:

TABLE MAS:
ID | COLOR | CITY |
0 | Blue | San Deigo |
1 | Blue | Las Vegas |
2 | Blue | Los Angeles |
3 | Red | Las Vegas |
4 | Red | Reno |
5 | Orange | San Francisco |

The query wants to give result like so:

Color | Total | State
Blue | 2 | CA
Blue | 1 | NV
Red | 2 | NV
Orange | 1 | CA

Assuming I do need a state/city table I would create it like so:

ID | State | City
0 | CA | Los Angeles
1 | CA | San Deigo
2 | NV | Las Vegas
3 | NV | Reno
4 | CA | San Francisco

I got as far as :

Code:
SELECT MAS.color, MAS.city, Count(*) AS Expr1
FROM MAS
GROUP BY MAS.color, MAS.city;

But that query gives a total per city (rather than grouping the cities by state).

Thanks

-Al
 

jdraw

Super Moderator
Staff member
Local time
Today, 07:20
Joined
Jan 23, 2006
Messages
15,379
What do you want as final format/result?

SELECT MAS.COLOR, CityState.State, Count(MAS.COLOR) AS CountOfCOLOR
FROM MAS INNER JOIN CityState ON MAS.CITY = CityState.City
GROUP BY MAS.COLOR, CityState.State;

COLOR State CountOfCOLOR
Blue CA 2
Blue NV 1
Orange CA 1
Red NV 2
 

bigal.nz

Registered User.
Local time
Today, 23:20
Joined
Jul 10, 2016
Messages
92
What do you want as final format/result?

SELECT MAS.COLOR, CityState.State, Count(MAS.COLOR) AS CountOfCOLOR
FROM MAS INNER JOIN CityState ON MAS.CITY = CityState.City
GROUP BY MAS.COLOR, CityState.State;

COLOR State CountOfCOLOR
Blue CA 2
Blue NV 1
Orange CA 1
Red NV 2

What you have done looks like exactly what I want - I assume its based on a table mapping city to state called CityState?
 

arnelgp

..forever waiting... waiting for jellybean!
Local time
Today, 19:20
Joined
May 7, 2009
Messages
19,245
You need to add the state/city id to table MAS.
 

Dystonia

Access 2002, 2010, 2016
Local time
Today, 12:20
Joined
Nov 11, 2017
Messages
17
If you only have a few cities, use could the SWITCH function ?

SELECT Switch(City='San Diego','CA',City='Las Vegas','NV') as State

...not recommended though if you have thousands of cities and 50 states
 

jdraw

Super Moderator
Staff member
Local time
Today, 07:20
Joined
Jan 23, 2006
Messages
15,379
I used a statecity table
 

Attachments

  • QueryDesign.png
    QueryDesign.png
    17 KB · Views: 66

bigal.nz

Registered User.
Local time
Today, 23:20
Joined
Jul 10, 2016
Messages
92
What do you want as final format/result?

SELECT MAS.COLOR, CityState.State, Count(MAS.COLOR) AS CountOfCOLOR
FROM MAS INNER JOIN CityState ON MAS.CITY = CityState.City
GROUP BY MAS.COLOR, CityState.State;

COLOR State CountOfCOLOR
Blue CA 2
Blue NV 1
Orange CA 1
Red NV 2

Perfect. Thank you.
 

Users who are viewing this thread

Top Bottom