我有客户 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;
关于postgresql - 使用 lag 函数 postgres 的日期差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46510908/