如何获取上一年的数据?

How to get data from previos year?

这是我的基本样本 我需要在 Hello table

中获取上一时期的滞后数据

你能帮帮我吗?

+------+--------+------+-------+
| Year | Animal | Plus | Hello |
+-------+------+--------+------+
|    2 | Cat    |    3 |       |
|    2 | Dog    |    4 |       |
|    2 | Mouse  |    5 |       |
|    3 | Cat    |    5 |     3 |
|    3 | Dog    |    6 |     4 |
|    3 | Mouse  |    6 |     5 |
|    3 | Horse  |    6 |       |
|    3 | Pig    |    6 |       |
|    3 | Goose  |    6 |       |
|    4 | Cat    |      |     5 |
|    4 | Dog    |      |     6 |
|    4 | Mouse  |      |     6 |
|    4 | Horse  |      |     6 |
|    4 | Pig    |      |     6 |
+-------+------+--------+------+

您正在寻找 LAG。此函数查看前几行。

select
  place, year, animal, plus,
  lag(plus) over (partition by animal order by year) as hello
from mytable
order by year, animal;

“上一”行是最近的前一行,即如果“Goose”有第 3 年和第 5 年的行,none第 4 年的行,则第 3 年将被视为前一行第 5 年和 LAG 将显示该值。

如果你真的想要相邻的前一年,即year - 1,那么你可以select今年如下:

select
  place, year, animal, plus,
  (
    select plus
    from mytable prev_year
    where prev_year.animal = mytable.animal
    and prev_year.year = mytable.year - 1)
  ) as hello
from mytable
order by year, animal;

外连接也一样:

select
  t.place, t.year, t.animal, t.plus, prev_year.plus as hello
from mytable t
left join mytable prev_year on prev_year.animal = t.animal
                           and prev_year.year = t.year - 1
order by t.year, t.animal;