我尝试针对World Database的城市表编写查询,该表同时计算每个国家/地区的重复城市数量以及重复值。这部分是有效的,但我也希望显示每个国家的重复城市总数。
到目前为止,这是我的SQL(仅限于一个用于测试的国家/地区):
Select c1.country_code, c1.city, citc.city_duplicates
from cities c1
join
(SELECT c2.id, c2.country_code, c2.city, COUNT(c2.city) AS `city_duplicates`
FROM cities c2
WHERE c2.country_code = 'om'
GROUP BY country_code, region_code, latitude, longitude, city
HAVING city_duplicates > 1
ORDER BY country_code) citc
on c1.id = citc.id;
以下是结果:
# country_code, city, city_duplicates
'om', 'zi', '2'
'om', 'zi', '2'
我希望看到另一栏中写着' 4'为国家总数。
如果你可以用desc顺序的重复数排序,那么可以获得奖励积分。
以下是一些示例数据:
# country_code, city, accent_city, region_code, population, latitude, longitude, id
'om', 'abailah', 'Abailah', '02', '0', '24.266666', '56.150002', '2050634'
'om', 'a`bal', 'A`bal', '05', '0', '24.433332', '56.049999', '2050635'
'om', '`abat', '`Abat', '04', '0', '22.550556', '59.328056', '2050636'
'om', '`abayah', '`Abayah', '06', '0', '23.175278', '58.814167', '2050637'
'om', '`abbasah', '`Abbasah', '02', '0', '23.916668', '57.216667', '2050638'
'om', '`ablah', '`Ablah', '05', '0', '23.168333', '56.909168', '2050639'
'om', 'abu `abali', 'Abu `Abali', '02', '0', '23.771111', '57.676945', '2050640'
'om', 'abu akaisha', 'Abu Akaisha', '04', '0', '21.400000', '59.283333', '2050641'
om zi Z̧ahir 00 0 19.100000 56.966667 2053410
om zi Z̧abyah 02 0 24.350000 56.366669 2053408
ad aixirivall Aixirivall 06 0 42.466667 1.500000 3
ad aixirvall Aixirvall 06 0 42.466667 1.500000 4
ad aixovall Aixovall 06 0 42.466667 1.483333 5
ad andorra Andorra 07 0 42.500000 1.516667 6
以下是国家/地区的结果:
# country_code, city, city_duplicates, country_duplicates
'om', 'zi', '2', '4'
'om', 'zi', '2', '4'
谢谢!
答案 0 :(得分:1)
如果要在另一列中显示总和,您几乎必须总结外部查询中的city_duplicates
字段并将其连接到子查询的结果:
SELECT c2.country_code, c2.city, COUNT(c2.city) AS `city_duplicates`, t2.country_duplicates
FROM cities c2
INNER JOIN (SELECT t.country_code, SUM(t.city_duplicates) as country_duplicates
FROM (SELECT c3.country_code, c3.city, COUNT(c3.city) AS `city_duplicates`
FROM cities c3
WHERE c3.country_code = 'om'
GROUP BY country_code, region_code, latitude, longitude, city
HAVING city_duplicates > 1) t
GROUP BY t.country_code) t2 ON c2.country_code=t2.country_code
WHERE c2.country_code = 'om'
GROUP BY c2.country_code, region_code, latitude, longitude, city
HAVING city_duplicates > 1
ORDER BY country_duplicates, c2.country_code
但是,如果您希望将摘要放在单独的记录中,那么代码会简单得多,因为您可以使用MySQL的rollup group by`修饰符。
答案 1 :(得分:0)
只需计算您的城市重复次数
Select c1.country_code, c1.city, citc.city_duplicates ,sum(citc.city_duplicates) as country_duplicate
from cities c1
join
(SELECT c2.id, c2.country_code, c2.city, COUNT(c2.city) AS `city_duplicates`
FROM cities c2
WHERE c2.country_code = 'om'
GROUP BY country_code, region_code, latitude, longitude, city
HAVING city_duplicates > 1
ORDER BY country_code) citc
on c1.id = citc.id group by c1.country_code order by c1.country_code desc;