Sql 从多个表中获取信息的查询
我正在编写一组查询,这些查询从多个表中获取信息,或者实际使用子查询来初始化它们。我现在遇到问题的查询实际上应该是生成两个表中都没有的另一个字段。我正在写的查询的确切定义如下 列出国家名称、人口以及该国所有城市的人口总数。在查询中添加第四个字段,用于计算每个国家的城市人口百分比。(在本例中,假设一个国家列出的所有城市的人口总和代表该国的全部城市人口。)按城市人口百分比的递增顺序排列此查询的结果 我为这个查询尝试的代码如下Sql 从多个表中获取信息的查询,sql,database,postgresql,Sql,Database,Postgresql,我正在编写一组查询,这些查询从多个表中获取信息,或者实际使用子查询来初始化它们。我现在遇到问题的查询实际上应该是生成两个表中都没有的另一个字段。我正在写的查询的确切定义如下 列出国家名称、人口以及该国所有城市的人口总数。在查询中添加第四个字段,用于计算每个国家的城市人口百分比。(在本例中,假设一个国家列出的所有城市的人口总和代表该国的全部城市人口。)按城市人口百分比的递增顺序排列此查询的结果 我为这个查询尝试的代码如下 SELECT name, population, SUM(populatio
SELECT name, population, SUM(population) FROM what.country JOIN what.city ON city.country_code =
country.country_code GROUP BY population 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
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
你已经解决了大部分问题-唯一缺少的是城市人口的百分比,你可以通过将城市人口(你已经计算过)的总和除以总人口来实现:
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
感觉像是家庭作业周@stackoverflowツ 重复作业。今年9月下旬,似乎是这样。是的,有人开的课教得不好,或者除了讲课之外没有适当的辅导课。Ryan,作业在堆栈溢出上是可以的,但请说这是作业或作业。如果你继续发帖的话,我会投反对票和弃权票。你在密苏里州用@jimmy做CMP_SC 3380,对吗?“6号实验室”?谢谢你,这正是我所困惑的,你帮了我很多忙@mureinik当我尝试这个的时候,我实际上犯了一个错误。这是查询失败的错误:错误:语法错误位于或接近“ASC”行6:GROUP BY cnt.name ASC^in@ryan是的,我犯了个愚蠢的错误。雷达的编辑应该已经修复了它-请看现在。