我有客户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并使用滞后函数提取,但我收到错误
函数滞后(没有时区的时间戳)只能被称为窗口函数
我正在寻找下面的结果
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中找到差异?
答案 0 :(得分:0)
这是你想要的吗?
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;