Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Storing the minimum event time for each user id in the same table in SQL

I’m using snowflake to solve a problem. I’m trying to find the minimum event time for each user id and store it in another column in the same table.

For instance,

user_id client_event_time
1 2022-07-28
1 2022-08-04
1 2022-08-21
2 2022-07-29
2 2022-07-31
2 2022-08-03

I want to store it like the following:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

user_id client_event_time MinEventTime
1 2022-07-28 2022-07-28
1 2022-08-04 2022-07-28
1 2022-08-21 2022-07-28
2 2022-07-29 2022-07-29
2 2022-07-31 2022-07-29
2 2022-08-03 2022-07-29

I started with the following SQL query:

  SELECT user_id,client_event_time, 
    row_number() over (partition by user_id order by client_event_time) row_number,
    case 
        when row_number = 1  then client_event_time
     end as MinEventTime
    FROM Data
    ORDER BY user_id, client_event_time;
user_id client_event_time row_number MinEventTime
1 2022-07-28 1 2022-07-28
1 2022-08-04 2 Null
1 2022-08-21 3 Null
2 2022-07-29 1 2022-07-29
2 2022-07-31 2 Null
2 2022-08-03 3 Null

I’m a little confused about how to proceed after this. I would also appreciate a suggestion on another approach. Thanks!

>Solution :

You may also use MIN() here as an analytic function:

SELECT user_id, client_event_time,
       ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY client_event_time) row_number,
       MIN(client_event_time) OVER (PARTITION BY user_id) MinEventTime
FROM Data
ORDER BY user_id, client_event_time;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading