Earliest date of the latest ID
Hi,
I am trying to get the earliest start time of the latest plan that the person took. In the following, the latest plan is P1, and the earliest start date of it is 06-Feb-2015 . It should therefore return P1 , 06-Feb-2015
ID Date Plan Bundle
100 03-Jan-2014 P1 12
100 13-Oct-2014 P2 07
100 21-Dec-2014 P2 09
100 06-Feb-2015 P1 11
100 06-Nov-2015 P1 13
100 18-Apr-2016 P1 14
Ive tried a few ways to get it, but Im not getting thru. Appreciate any assistance pleaseee
Thanks!
0
Comments
Why wouldn't the Date be 2014-01-03? That's the earliest date for P1.
It can be easily written as:
Select foo.plan,foo.date from ( select plan, date from test where plan = ( select min(plan) from test ) foo order by 2 limit 1;
@RaghavA I thought that also. In fact I was going to suggest this:
But the "latest plan" isn't the first plan alphabetically I think it is just a coincidence in the sample data.
I think what we're looking for is the start-date and end-date for the latest 'session' of plan P1. Customer started at plan P1, then went to P2 stayed on P2 and went back to P1. So something like this:
------------+------------+------
2015-02-06 | 2016-04-18 | P1
(1 row)
WITH mydata AS
(SELECT
ID ,Date ,Plan ,Bundle
, CONDITIONAL_TRUE_EVENT(Plan <> LAG(Plan) )
OVER (PARTITION BY ID ORDER BY Date)
AS session_id
FROM mytb
)
select min(Date), max(Date), Plan
from mydata
where session_id = (select session_id from mydata where Date = (select max(Date) from mydata))
group by Plan
;
....hope this makes sense!
@peterjansens: That makes sense! I guess there are a million ways to write the SQL
Nice, the 'limit 1' function has always lived in my mind as 'something for testing', but there is no reason to limit (pun intended) it as such.
Thanks everyone! I got thru with your suggestions. I used :
dbadmin=> select Plan, Date from (select Plan, Date, conditional_change_event(Plan) over (partition by id order by Date) rn from test order by rn desc, Date limit 1) foo;
I was looking for the current Plan they are on, which is P1, and when they started/switched to it ..which is 2015-02-06
Thanks so much!!