postgresql - 使用 lag 函数 postgres 的日期差异

标签 postgresql datediff

我有客户 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/

相关文章:

PostgreSQL:删除用户或删除角色?

hibernate - 可能的错误 : Hibernate 4. 3.5 @Lob 注释在用于字段时在 Postgres 中不起作用

sql-server-2012 - DateDiff - 夏令时问题

mysql - 具有唯一 ID 的高级平均日期差异

mysql - 如果值不为空,则为 DATEDIFF

mysql - mysql 中两个日期的总天数

javascript - 脚本不工作。 Lint 说需要分号

postgresql - 如何在没有备份的情况下恢复 postgresql 数据库

postgresql - 在 Postgres 中对非常大的结果集正确使用游标

sql - 如何创建没有循环关系的树表?