Home > Net >  Identify if date is the last date for any given group?
Identify if date is the last date for any given group?

Time:08-01

I have a table that is structured like the below - this contains details about all customer subscriptions and when they start/end.

SubKey CustomerID Status StartDate EndDate
29333 102 7 01 jan 2013 1 Jan 2014
29334 102 6 7 Jun 2013 15 Jun 2022
29335 144 6 10 jun 2021 17 jun 2022
29336 144 2 8 oct 2023 10 oct 2025

I am trying to add an indicator flag to this table (either "yes" or "no") which shows me by each row, if when the [EndDate] of the SubKey is the last one for that CustomerID. So for the above example..

SubKey CustomerID Status StartDate EndDate IsLast
29333 102 7 01 jan 2013 1 Jan 2014 No
29334 102 6 7 Jun 2013 15 Jun 2022 Yes
29335 144 6 10 jun 2021 17 jun 2022 Yes
29336 144 2 8 oct 2023 10 oct 2025 Yes

The flag is set to No for the first row, because on 1 Jan 2014, customerID 102 had another SubKey (29334) still active at the time (which didn't end until 15 jun 2022)

The rest of the rows are set to "Yes" because these were the last active subscriptions per CustomerID.

I have been reading about the LAG function which may be able to help. I am just not sure how to make it fit in this scenario.

CodePudding user response:

Probably the easiest method would to use exists with a correlation. Can you try the following for your desired results for excluding rows without an overlap:

select *, 
  case when exists (
    select * from t t2 
    where t2.customerId = t.customerId 
      and t2.enddate > t.enddate 
      and t2.startDate < t.Enddate
  ) then 'No' else 'Yes' end as IsLast
from t;
  • Related