[英]count and sum the values sql
I have two tables: BORDERS with country1,county2 ,COUNTRYPOPS with country,year and population, and I want for each country, list its population and the total population of all neighboring countries.(and if it has no neighboring countries, NULL) so far I can find the max population for each country and how many neighbors each country has, but I cannot find a way to sum up the population of all neighbor countries. 我有两个表:BORDERS(具有country1,county2),COUNTRYPOPS(具有国家,年份和人口),我想为每个国家/地区列出其人口和所有邻近国家的总人口。(如果没有邻近国家,则为NULL)到目前为止,我无法找到每个国家的最大人口以及每个国家有多少个邻国,但是我无法找到一种方法来总结所有邻国的人口。 Any Ideas?
有任何想法吗?
SELECT country, MAX(population) FROM COUNTRYPOPS GROUP BY 1 ORDER BY 1
---------------
SELECT countries, COUNT(countries) as have_borders
FROM
( SELECT country1 AS countries
FROM borders
UNION ALL
SELECT country2
FROM borders ) t
GROUP BY countries
ORDER BY countries;
How about something like 怎么样
SELECT country, pop, SUM(cc.population) AS neighboursPop
FROM (
SELECT c.country AS country, c.population AS pop, b.country2 AS neighbour
FROM countrypops c
LEFT JOIN borders b ON b.country1 = c.country
) t
LEFT JOIN countrypops cc ON cc.country = t.neighbour
GROUP BY country;
Didn't test it, but the idea is that. 没有测试它,但是想法是那样的。
UPD: or it could even be flattened like UPD:或者甚至可以像
SELECT country, pop, SUM(neighPop) AS neighboursPop
FROM (
SELECT
c.country AS country,
c.population AS pop,
b.country2 AS neighbour,
cc.population AS neighPop
FROM countrypops c
LEFT JOIN (borders b
LEFT JOIN countrypops cc ON cc.country = b.country2)
ON b.country1 = c.country
) t
GROUP BY country;
I think a correlated subquery is the easiest way: 我认为相关子查询是最简单的方法:
select cp.country, cp.pop,
(select sum(cp2.pop)
from borders b join
countrypops cp2
on b.country2 = cp2.country
where b.country1 = cp.country
) as neighboring_pop
from countrypops cp;
This does not have an aggregation in the outer query, so it should be more efficient than an approach that does. 它在外部查询中没有聚合,因此它应该比这样做的方法更有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.