我从sql查询获得此结果。该表的名称为“人口”,其列为:地区,国家/地区,城市,year_v和人口:
REGION COUNTRY CITY YEAR_V POPULATION
europe france paris 2015 2.1
europe france paris 2017 2.2
europe france lyon 2016 .4
europe spain madrid 2012 2.9
europe spain madrid 2013 3
europe spain madrid 2014 3.1
europe spain madrid 2016 .8
我需要从这里得到的是按城市划分的逐年人口趋势,它应该像这样:
city growth year_diff
Madrid 0.10 2012-2013
Madrid 0.10 2013-2014
Paris 0.10 2015-2017
对于如何编写可以返回这种结果的查询的提示,我将不胜感激。
答案 0 :(得分:3)
您将使用lag()
:
select region, country, city,
year_v, population,
prev_year_v, prev_population,
(population - prev_population) as diff
from (select t.*,
lag(population) over (partition by region, country, city order by year_v) as prev_population,
lag(year_v) over (partition by region, country, city order by year_v) as prev_year_v,
from t
) t
where prev_year_v is not null;