Reputation: 145
I have two tables: Table A has today's data and Table B has the historical snapshot of the data captured on a daily basis.
**Table A**
User Status Date (which is current_date)
A1 A 12/23/2019
B1 B 12/23/2019
**Table B**
User Status Date
A1 B 12/20/2019
A1 A 12/21/2019
A1 B 12/22/2019
A1 A 12/23/2019
B1 A 12/20/2019
B1 B 12/21/2019
B1 A 12/22/2019
B1 B 12/23/2019
What I am looking for are: in 2019
Thanks!
Upvotes: 0
Views: 358
Reputation: 1269443
Basically, you want lag()
and last_value()
. Table A
does not seem necessary.
The basic logic to get what you want is:
select b.*
from (select b.*,
last_value(status) over (partition by user order by date) as last_status,
lag(status) over (partition by user order by date) as prev_status
from b
) b
where date >= '2019-01-01' and
date < '2020-01-01' and
((last_status = 'B' and status = 'B' and prev_status = 'A') or
(last_status = 'B' and status = 'B' and prev_status = 'A') or
(last_status = 'A' and status = 'A' <> prev_status)
)
Upvotes: 1