I have a sample data as below and wanting to get a desired o/p, please help me with some idea.
I want the o/p of prev_diff_value of the 3rd,4th row to be 2015-01-01 00:00:00 instead of 2015-01-02 00:00:00.
with dat as (
select 1 as id,'20150101 02:02:50'::timestamp as dt union all
select 1,'20150101 03:02:50'::timestamp union all
select 1,'20150101 04:02:50'::timestamp union all
select 1,'20150102 02:02:50'::timestamp union all
select 1,'20150102 02:02:50'::timestamp union all
select 1,'20150102 02:02:51'::timestamp union all
select 1,'20150103 02:02:50'::timestamp union all
select 2,'20150101 02:02:50'::timestamp union all
select 2,'20150101 03:02:50'::timestamp union all
select 2,'20150101 04:02:50'::timestamp union all
select 2,'20150102 02:02:50'::timestamp union all
select 1,'20150104 02:02:50'::timestamp
)-- select * from dat
select id , dt , lag(trunc(dt)) over(partition by id order by dt asc) prev_diff_value
from dat
order by id,dt desc
O/P :
id dt prev_diff_value
1 2015-01-04 02:02:50 2015-01-03 00:00:00
1 2015-01-03 02:02:50 2015-01-02 00:00:00
1 2015-01-02 02:02:51 2015-01-02 00:00:00
1 2015-01-02 02:02:50 2015-01-02 00:00:00
1 2015-01-02 02:02:50 2015-01-01 00:00:00