I have this table:
ts | user_id | event |
-------------------------------
1500 a eat
1501 a walk
1502 a sleep
1500 b eat
1501 b sleep
1502 b wake
1500 c walk
1501 c eat
1502 c sit
1503 c sleep
1504 c wake
So I want to select x number of rows prior to a certain event, let's say I want to select 2 events before sleep per user_id.
My final table result should look like:
user_id | event | rank |
--------------------------------
a eat 1
a walk 2
a sleep 3
b NULL 0
b eat 1
b sleep 2
c eat 2
c sit 3
c sleep 4
How to do this in SQL (specifically Redshift SQl)