sql - PostgreSQL 计算行之间的差异

标签 sql postgresql

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

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

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

根据修复中相邻行之间的差异增加列作为输出。

最佳答案

这就是窗口函数的用途:

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

关于sql - PostgreSQL 计算行之间的差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24691462/

相关文章:

sql - 向 postgres 查询添加查询参数时出错

sql - 是否可以撤消回滚?

sql - 如何查询用户与所有其他用户之间的评分平均差异

mysql - 动态添加列到sql结果

mysql - 我有两个表,第一个表 T1 包含 id 和 name,名称包含 5 个值

MySQL 唯一行

ruby-on-rails - Rails5/强参数/带有 'dynamic' 键的 json 列

mysql - 所有类型的 SQL 连接的解释

MySQL 如何找到具有确切子集的父项?

postgresql - 更改表错误添加 2 列