SQL - 从两个表中查询

时间:2012-12-07 05:25:12

标签: sql postgresql

对于一个项目,我必须编写两个表并对它们进行查询。我编写了表格,但需要对查询部分提供一些指导。

这是第一张表。

CREATE TABLE Country
(Name VARCHAR(35) NOT NULL UNIQUE,
Code VARCHAR(4) CONSTRAINT CountryKey PRIMARY KEY,
Capital VARCHAR(35),
Province VARCHAR(35),
Area NUMERIC CONSTRAINT CountryArea
    CHECK (Area >= 0),
Population NUMERIC CONSTRAINT CountryPop
    CHECK (Population >= 0));

这是第二张表。

CREATE TABLE City
(Name VARCHAR(35),
Country VARCHAR(4),
Province VARCHAR(35),
Population NUMERIC CONSTRAINT CityPop
    CHECK (Population >= 0),
Longitude NUMERIC CONSTRAINT CityLon
    CHECK ((Longitude >= -180) AND (Longitude <= 180)) ,
Latitude NUMERIC CONSTRAINT CityLat
    CHECK ((Latitude >= -90) AND (Latitude <= 90)) ,
CONSTRAINT CityKey PRIMARY KEY (Name, Country, Province));

我的查询必须执行以下操作:

Return the min, max, and average latitude of all cities for all the countries in the table. 
And should be ordered by continent first and country second.

这是在PostgreSQL中。

感谢您的时间。

1 个答案:

答案 0 :(得分:1)

你没有在你的问题中透露RDBMS:它是MySQL 还是 PostgreSQL?

但是,这应该适用于:

SELECT 
      continent -- not quite sure what this refers to
    , ctr.Code AS country_code
    , avg(city.latitude) AS avg_population
    , min(city.latitude) AS min_population
    , max(city.latitude) AS max_population
FROM
    country ctr
    JOIN city ON ctr.Code = city.Country
GROUP BY 
      continent
    , ctr.Code
ORDER BY 
      continent
    , ctr.Code
;

GROUP BY子句使计算值引用ctr.Code。