PostgreSQL计算行之间的差异 [英] PostgreSQL calculate difference between rows

查看:243
本文介绍了PostgreSQL计算行之间的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用查询来计算字段中行之间的差异:

I tried to calculate difference between rows in a field using a query:


Illustrations:
input:year,month,fixes
output:increase

     year | month | fixes    | increase
    ------+-------+----------+-----------
     2006 | 04    |       1  | 0
     2006 | 05    |       4  | 3
     2006 | 06    |       3  | -1

通过修订中相邻行之间的差异增加列作为输出。

Increase column as output by difference between adjacent rows in fixes.

推荐答案

这是窗口函数的作用:

select year, 
       month,
       fixes,
       fixes - lag(fixes) over (order by year, month) as increase,
from the_table;

有关更多详细信息,请参见手册:

http://www.postgresql.org/docs/current/static/tutorial-window.html

For more details please see the manual:
http://www.postgresql.org/docs/current/static/tutorial-window.html

这篇关于PostgreSQL计算行之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆