0

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

这是第一张桌子。

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 中。

感谢您的时间。

4

1 回答 1

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。

于 2012-12-07T05:33:36.493 回答