我有以下表COUNTRY_PEOPLE:
COUNTRY - CITY - YEAR - PEOPLE
ENGLAND - LONDON 1980 - 7834020
ENGLAND - LONDON 2010 - 8308369
ENGLAND - DERBY 1980 - 231483
ENGLAND - DERBY 2010 - 233700
FRANCE - PARIS 1980 - 2174654
FRANCE - PARIS 2010 - 2274880
FRANCE - NANTES 1980 - 279321
FRANCE - NANTES 2010 - 290130
我需要一个SQL查询来获取每个国家/地区的城市列表,其中包含2010年和1980年之间的人员差异。 所以:
ENGLAND - LONDON 474349
ENGLAND - DERBY 2217
FRANCE - PARIS 100226
FRANCE - NANTES 10809
然后是国家的平均值,但这应该是一组很容易的。 我刚刚从一个真实无聊的场景中发明了这个例子,所有数据都是假的。 提前谢谢
答案 0 :(得分:1)
尝试:
SELECT Country, City,
AVG(CASE WHEN Year=2010 THEN People END)-AVG(CASE WHEN Year=1980 THEN People END) as AvgPeople
FROM COUNTRY_PEOPLE
GROUP BY Country, City
参见 Demo
<强>结果强>:
答案 1 :(得分:1)
请检查以下查询
SELECT a.COUNTRY,a.CITY,(ISNULL(a.PEOPLE,0) - ISNULL(b.PEOPLE,0)) AS PEOPLE
FROM
(SELECT COUNTRY ,CITY , SUM(ISNULL(PEOPLE,0)) AS PEOPLE FROM COUNTRY_PEOPLE
WHERE [YEAR] = 2010 GROUP BY COUNTRY ,CITY) a
LEFT OUTER JOIN
(SELECT COUNTRY ,CITY , SUM(ISNULL(PEOPLE,0)) AS PEOPLE FROM COUNTRY_PEOPLE
WHERE [YEAR] = 1980 GROUP BY COUNTRY ,CITY)
b ON a.COUNTRY = b.COUNTRY AND a.CITY = b.CITY
答案 2 :(得分:0)
怎么样:
select c1.Country,c1.City,(c1.People-c2.People) as Diff from Country_people c1
join Country_people c2 on c1.Country = c2.Country and c1.City = c2.City and c1.Year = 2010 `and c2.Year = 1980`