0

I have the following structure of a MySQL first table:

http://www.clubmadam.com/zadatak.jpg

Structure of a MySQL second table:

http://www.clubmadam.com/country.jpg

I need an SQL query to count number of cities in each country and summarise population for all cities in country;

This is what I have so far:

$upit = "SELECT";
$rezultat = mysql_query($upit);
{
}

Can a MySQL handle this, or do I need to also use PHP? How would I do this?

5 Answers 5

1

This really is SQL 101 stuff, I suggest you do a lot of reading

SELECT CountryCode,
       COUNT(Name) as Cities,
       SUM(Population) as Population
  FROM <tablename>
 GROUP BY CountryCode
Sign up to request clarification or add additional context in comments.

1 Comment

I think he wanted a count by Country Code (# cities in ESP, # cities in UKR etc.) GROUP BY Name will give him duplicated name values.
1

If I understand correctly, this query will give a count of cities based on country:

SELECT COUNT(*) AS CityCount, CountryCode, SUM(Population) AS CountryPopulation
FROM myTableName
GROUP BY CountryCode

Per your comment, here is how you can do it across multiple tables:

SELECT City.COUNT(*) AS CityCount, Country.LocalName, City.SUM(Population) AS CountryPopulation
FROM City, Country
GROUP BY City.CountryCode

2 Comments

Txank mate this works like charm, can you help me a little more, i have just one table that i have JOIN to get all the results. [link]clubmadam.com/country.jpg The first table is CITY and second table is COUNTRY, i need when some ask city name, Has to have how many cities in that country, and population by all cities, txanks in advance
I updated the answer. It should work but if you have problems you can ask.
0

This is a simple MySQL aggregation job using the SUM() and COUNT() aggregate funcions:

$sql = 'SELECT 
  CountryCode, 
  COUNT(ID) as numCities, 
  SUM(Population) as totalPopulation 
  FROM Cities 
  GROUP BY CountryCode';

Comments

0
$upit = "SELECT COUNT(ID) AS cities, SUM(Population) AS population, ContryCode FROM table GROUP BY CountryCode";
$result = mysql_query($upit);
while ($data = mysql_fetch_object($result)) {
    // $data->cities is the number of cities and $data->population the sum of people and $data->CountryCode the country code
}

Comments

0

Count number of cities in Country-code

$upit = "SELECT COUNT(DISTINCT CountryCode) FROM table_name
$num_rows = mysql_num_rows($upit);
echo "$num_rows Rows\n";

Summarize population for all cities in Country-code

Refer @Mark Baker Answer

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.