Question

I have a table (MySQL InnoDB) of companies with respective address. A company serve clients of it city. With that, I included a column to set others regions (states) the company can serve, and other column to set if the company serve all the country:

id  State   City            Street      Name            OtherRegions    serveCountry
----------------------------------------------------------------------------------------
1   CA      Los Angeles     Street      Microsoft       NULL            NULL
2   NY      New York        Street2     Mercur chip     CA              NULL
3   NY      Buffalo         street3     apple inc       NULL            1
4   TX      Houston         street4     Climp corp      CA;NY           NULL
5   CA      San Francisco   street5     Motorola        NULL            NULL
6   TX      San Antonio     street6     HP Inc.         NULL            NULL
7   CA      San Francisco   street7     sony            NULL            NULL

My question is: How can I get the cities of the specific state with the count of companies which serve the respective city?

Expected results:

CA state

City            Number of Companies serve
-----------------------------------------------------------
Los Angeles     4 (Microsoft, Mercur, Apple, Climp)
San Francisco   4 (Mercur, Apple, Climp, Motorola, Sony)

NY State

City            Number of Companies serve
-----------------------------------------------------------
New York        3 (Mercur, Apple, Climp)
Buffalo         2 (Apple, Climp)

Can I do it in the same query or I have to do that in multiple queries (PHP)?

Let's assume don't have regions/sub-regions exceptions.

Thanks a lot!!

Was it helpful?

Solution

You can use group by to get a list of the cities and number_of_companies serve but this wont give the companies in ().

Select city, count(*) as 'Number of companies serve'
from some_table
group by state

Your table assumes that companies all serve a city within the state they are in. It also is wont be possible to list all the companies that serve a city since that info isn't in your table, unless you assume a company serves all the cities in its OtherRegions?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top