使用滞后函数postgres的日期差异

Difference of dates using lag function postgres

我有如下所示的客户 ID 和交易日期 (yyyy-mm-dd)

Cust_id Trans_date
1       2017-01-01
1       2017-01-03
1       2017-01-06
2       2017-01-01
2       2017-01-04
2       2017-01-05

我需要找出在 Cust_id

处分组的每笔交易在 no_of_days 中的差异

我尝试使用 date_diff 并使用滞后函数提取,但出现错误

function lag(timestamp without time zone) may only be called as a window function

我正在寻找如下结果

Cust_id Trans_date difference
1       2017-01-01   0
1       2017-01-03   3
1       2017-01-05   2 
2       2017-01-01   0
2       2017-01-04   4
2       2017-01-05   1

如何找出postgreSQL中的差异?

这就是你想要的?

with t(Cust_id,Trans_date) as( 
    select 1       ,'2017-01-01'::timestamp union all
    select 1       ,'2017-01-03'::timestamp union all
    select 1       ,'2017-01-06'::timestamp union all
    select 2       ,'2017-01-01'::timestamp union all
    select 2       ,'2017-01-04'::timestamp union all
    select 2       ,'2017-01-05'::timestamp 
)

select 
Cust_id, 
Trans_date, 
coalesce(Trans_date::date - lag(Trans_date::date) over(partition by Cust_id order by Trans_date), 0) as difference
from t;