【问题标题】:Difference of dates using lag function postgres使用滞后函数 postgres 的日期差异
【发布时间】:2018-03-12 15:53:59
【问题描述】:

我有如下所示的客户 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 并使用 lag 函数进行提取,但出现错误

function lag(timestamp without time zone) 只能作为窗口函数调用

我正在寻找如下结果

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 中如何找出不同之处?

【问题讨论】:

    标签: postgresql datediff


    【解决方案1】:

    这就是你想要的?

    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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-11
      • 2013-08-23
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 1970-01-01
      • 2019-04-07
      • 2020-02-19
      相关资源
      最近更新 更多