简体   繁体   中英

SQL Excercise part 2

I am stuck on another SQL exercise, here is the question:

Show the 20 biggest cities in the United States along with their rank in the state (with respect to their population) and percent of the city population in a state (call it: perc_pop_state).

Here is what i have so far. This produces the table i am looking for, but for some weird reason the percentages of city population to state population are 0's for all the states with multiple cities and 1 for all states with one city. Can anyone guide me as to what is wrong with my code.

select
city.name, city.population, city.district, rank() over (partition by district order by city.population desc), city.population / sum(city.population) over (partition by district) as perc_pop_state
from 
city
inner join country on code = countrycode
where
country.name = 'United States'
order by 
city.population desc

ER图

I don't know which database this is for, but most likely it's because you the figures are not decimal data type - they are whole numbers, so when you divide them the result is a whole number (0 or 1) rather than a fraction. So you should use something like this

CAST(city.population AS DECIMAL(19,4)) 
      / 
CAST(sum(city.population) AS DECIMAL(19,4))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM