使用SQL中的连接查询从两个不同的表中使用第三个表重写两列的计数

时间:2016-09-08 09:25:26

标签: sql oracle

我有3个表:COUNTRYSTATECITY

这是我的Country表,有两列:

CountryID, Name

这是我的State表:

state table

这是我的City表:

city table

我想使用连接查询根据country表检索州和城市的数量。

1 个答案:

答案 0 :(得分:0)

跳过你的问题没有被问到好的事实 - 尝试这个查询,它应该适合你:

WITH
tab_a AS (
SELECT c.countryid, COUNT (s.stateid) AS state_num
FROM country c
LEFT JOIN state s ON c.countryid = s.countryid
GROUP BY c.countryid
),
tab_b AS (
SELECT c.countryid, COUNT (cc.cityid) city_num
FROM country c
LEFT JOIN state s ON c.countryid = s.countryid
LEFT JOIN city cc ON s.stateid = cc.stateid
GROUP BY c.countryid
)
SELECT a.countryid,
       a.state_num,
       b.city_num
FROM tab_a a JOIN tab_b b ON a.countryid=b.countryid