是否可以对同一列但不同行中的值进行数学运算?

Is it possible to do mathematical operations on values in the same column but different rows?

说我有这个 table,

 year |     name      | score
------+---------------+----------
 2017 | BRAD          |   5
 2017 | BOB           |   5
 2016 | JON           |   6
 2016 | GUYTA         |   2
 2015 | PAC           |   2
 2015 | ZAC           |   0

我将如何按年份计算平均分数,然后计算年份之间的差异?

 year |  increase
------+-----------
 2017 | 1
 2016 | 3

在这种情况下,您应该使用 window functionlead()

select year, avg, (avg - lead(avg) over w)::int as increase
from (
    select year, avg(score)::int
    from my_table
    group by 1
    ) s
window w as (order by year desc);

 year | avg | increase 
------+-----+----------
 2017 |   5 |        1
 2016 |   4 |        3
 2015 |   1 |         
(3 rows)