2014-10-13 5 views
0

쿼리를 실행하려고 할 때 오류가 발생하며 그 이유를 알 수 없습니다. 이것이 나의 숙제의 마지막 단계이며, 지금 당분간 그것을 알아 내려고 노력하고 있습니다. 내가 쓰려고하는 쿼리가 있습니다. 나는이에 대한이 코드는 내가 사용하고PHP의 여러 테이블에서 정보를 가져 오는 쿼리 작성

$query ="SELECT cnt.name AS country_name, 
cnt.population AS total_population, 
SUM(cty.population)/(cnt.population) * 100 AS urban_percentage 
FROM  what.country cnt 
JOIN  what.city cty ON cty.country_code = cnt.country_code 
GROUP BY cnt.name 
ORDER BY 3 ASC"; 

두 개의 테이블이

Table "what.country" 
    Column  |   Type   |    Modifiers    
-----------------+-----------------------+-------------------------------------- 
country_code | character(3)   | not null default ''::bpchar 
name   | character varying(52) | not null default ''::character varying 
continent  | continent    | not null 
region   | character varying(26) | not null default ''::character varying 
surface_area | real     | not null default 0::real 
indep_year  | smallint    | 
population  | integer    | not null default 0 
life_expectancy | real     | 
gnp    | real     | 
gnp_old   | real     | 
local_name  | character varying(45) | not null default ''::character varying 
government_form | character varying(45) | not null default ''::character varying 


    Table "what.city" 
    Column |   Type   |      Modifiers      
--------------+-----------------------+----------------------------------------- 
id   | integer    | not null default nextval('city_id_seq'::regclass) 
name   | character varying(35) | not null default ''::character varying 
country_code | character(3)   | not null default ''::bpchar 
district  | character varying(20) | not null default ''::character varying 
    population | integer    | not null default 0 
입니다

Warning: pg_query(): Query failed: ERROR: column "cnt.population" must appear in the 
GROUP BY clause or be used in an aggregate function LINE 2 

입니다

List the country name, it’s population, and the sum of the populations of all cities in 
that country. Add a fourth field to your query that calculates the percent of urban 
population for each country. (For the purposes of this example, assume that the sum of the 
populations of all cities listed for a country represent that country’s entire urban 
population.) Order the results of this query in increasing order of urban population 
percentage. 

내가 지금 수신하고 오류가있다

+1

에 대한 인구의 값은 하나만있을 것 집계됩니다. 이것은'cnt.population'의 경우입니다. – ForguesR

+0

@ForguesR 어떻게해야합니까? – jimmy

+0

감사합니다. 감사합니다. – jimmy

답변

0

도시 인구에 대해 MAX를 사용할 수 있습니다. 당신은 당신이 분류되지 않은 값이가는 얼마나 말할 가지고`GROUP BY` 절을 사용할 때 도시 이름을 GROUP BY을하고 있습니다로, 그 도시

$query ="SELECT cnt.name AS country_name, 
    Max(cnt.population) AS total_population, 
    SUM(cty.population), SUM(cty.population)/max(cnt.population) * 100 AS urban_percentage 
    FROM  what.country cnt 
    JOIN  what.city cty ON cty.country_code = cnt.country_code 
    GROUP BY cnt.name"; 
관련 문제