有一些新的(pg9.X)方式来表达一个依赖于两个相邻行的函数的查询吗?可以使用LATERAL吗?
示例:
C:\Users\your_user_name\AppData\Roaming\Neo4j Community Edition\neo4j-server.properties
如何用优雅的ID VAL DIFF NOTES
11 6 3 9-6=3
12 9 21 30-9=21
13 30 30 no row to subtract
表达DIFF(i) = VAL(i-1)-VAL(i)
?
PS:假设SELECT
答案 0 :(得分:3)
这可以使用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
访问 next 行的列值。如果没有下一行,则结果为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;