计算并汇总值sql

时间:2017-02-11 00:52:07

标签: sql

我有两张桌子:带有country1,county2,COUNTRYPOPS的国家,年份和人口的BORDERS,我想要每个国家,列出其人口和所有邻国的总人口。(如果没有邻国,空值) 到目前为止,我可以找到每个国家的最大人口数以及每个国家有多少邻居,但我找不到总结所有邻国人口的方法。任何想法?

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;

2 个答案:

答案 0 :(得分:0)

这样的东西
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;

没有测试,但想法就是。

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;

答案 1 :(得分:0)

我认为相关子查询是最简单的方法:

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;

这在外部查询中没有聚合,因此它应该比一种方法更有效。