Search code examples
sqlwindow-functions

Starting each SQL record from a specific point


I am wanting to figure out how to start each record from a specific point in SQL. I have created a data set to try and represent what I would like.

This is the starting data set.

enter image description here

However, I want to get a new view, with a defined starting point.

enter image description here

So each member record starts from ID 33 onwards, ordered by Member and Date. Basically want every record after ID 33 and the corresponding date for it.


Solution

  • If your ids are in order, you can use:

    select t.*
    from t
    where id >= 33
    order by member, date;
    

    If the ids are not in order, one method is a correlated subquery:

    select t.*
    from t
    where date >= (select min(t2.date) from t t2 where t2.member = t.member and t2.id = 33);
    

    And finally, a windows function approach is:

    select t.*
    from (select t.*,
                 min(case when id = 33 then date end) over (partition by member) as date_33
          from t
         ) t
    where date >= date_33;