sql - PostgreSQL 9.5 像电子表格一样优雅的查询

标签 sql postgresql

有一些新的 (pg9.X) 方法可以用依赖于两个相邻行的函数来表达查询吗?可以使用 LATERAL 吗?

示例:

ID   VAL   DIFF    NOTES
11   6     3       9-6=3
12   9     21      30-9=21
13   30    30      no row to subtract

如何用优雅的SELECT表达DIFF(i) = VAL(i-1)-VAL(i)
PS:假设ORDER BY "ID"

最佳答案

这可以使用 modern SQL 来完成喜欢window functions (从 Postgres 8.4 开始可用)

select id, 
       val, 
       lead(val) over (order by id) - val as diff
from the_table
order by id;

lead() 根据order by 访问 行的列值。如果没有下一行,则结果为 null,因此最后一行的减法结果也为 null。

编辑

如果你想使用具有相同窗口定义的多个窗口函数,你可以定义一次并重新使用它:

select id, 
       val, 
       lead(c1) over w - val as diff1, 
       lead(c2) over w - val as diff2
from the_table
window w as (order by id)
order by id;

关于sql - PostgreSQL 9.5 像电子表格一样优雅的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35441918/

相关文章:

sql - VS2010、SqlCE 4.0 没有数据源选项(只有3.5)

sql - 在 SQL 中合并 2 个结果集?

PostgreSQL,水平和垂直混合 SUM

postgresql - Postgres 实体化路径 - 使用 ltree 有什么好处?

python - PySpark - 写入 PostgreSQL DB 后获取插入的行 ID

postgresql - 在 PostgreSQL 中通过另一个表的值选择一列

mysql查询多列值的总和,其中列名来自选择列表

c# - 从用户在 asp.net c# 中输入的数据向 SQL Server 数据库添加行

php - 使用 MySQL 在一个查询中连接三个表

postgresql - 如何在Postgresql中删除所有以前缀开头的数据库