2015-02-11 69 views
0

我有两个数据库表。查询选择层次结构中类型的每个元素

Table A    Table B 

    Continent text  City    Text 
    Country text  Citizen ID (unique) Int  
    City  text  

如何编写一个查询,将在欧洲大陆,国家,城市,和(每个城市多的公民)的形式在特定的大陆内返回一行的每座城市?

如果我想进一步限制某个大陆和国家的每个城市,该怎么办?

我很难将查询视为除一系列嵌套for循环以外的内容。我有点不知道如何加入表格,以便我可以计算公民身份并获得必要的地理限制。如果我只是有点密集,我会提前道歉。

+1

它不清楚你在问什么可以添加总和输入数据和预期输出? – 2015-02-11 06:14:56

+0

你正在使用哪些DBMS? Postgres的?甲骨文? – 2015-02-11 09:23:54

回答

0

你没有提及你正在使用哪个DBMS,所以我假设MSServer。您可以将JoinCount得到row for every city within a particular continent in the form of Continent, Country, City, and (number of citizens per city)

SELECT 
     a.Continent, 
     a.Country, 
     a.City, 
     Count(b.CitizenID) AS 'NumberOfCitizens' 
    FROM 
    tableA a Join tableB b 
    ON a.City = b.City 
    WHERE 
    a.Continent = 'Yourcontinent' 
    Group By 
     a.Continent,a.Country,a.City, 

如果你想进一步限制,那么你可以添加条件在where子句中,
Ex.-为了限制对每一个国家,你可以在Where添加第

AND a.Country = 'Yourcountry' 

对于限制每一个城市,你可以在Where子句添加

 AND a.City = 'Yourcity' 

您可以阅读更多关于JoinWhere条款。