Это вариант проблемы групп и островов. Вы можете использовать разность номеров строк для описания группы:
select t.*,
dense_rank() over (partition by patient_id order by first_contact) as location_name
from (select t.*,
min(contact_date) over (partition by patient_id, location_name, seqnum - seqnum_2) as desired_result
from (select t.*,
row_number() over (partition by patient_id order by contact_date) as seqnum,
row_number() over (partition by patient_id, location_name order by contact_date) as seqnum_2
from t
) t
) t;
You can use the uuid library like so:
import uuid my_id = uuid.uuid1() # or uuid.uuid4()
import os, base64
def generate_session():
return base64.b64encode(os.urandom(16))
It can be as simple as creating a random number. Of course, you'd have to store your session IDs in a database or something and check each one you generate to make sure it's not a duplicate, but odds are it never will be if the numbers are large enough.