简体   繁体   English

SQL-从两个表查询

[英]SQL - Query from two tables

For a project, I had to write two tables and do a query on them. 对于一个项目,我必须编写两个表并对它们进行查询。 I have written the tables but need some guidance with the query part. 我已经写了表格,但是需要查询部分的一些指导。

Here is the first table. 这是第一张桌子。

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));

Here is second table. 这是第二张桌子。

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));

My query must do the following: 我的查询必须执行以下操作:

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.

This is in PostgreSQL. 这是在PostgreSQL中。

Thank you for your time. 感谢您的时间。

You don't disclose the RDBMS in your question: is it MySQL or PostgreSQL? 您不会在问题中透露RDBMS:是MySQL 还是 PostgreSQL?

However, this should work in both: 但是,这在两个方面都应该起作用:

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
;

The GROUP BY clause makes the computed values refer to the ctr.Code. GROUP BY子句使计算值引用ctr.Code。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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