Created
November 24, 2022 14:41
-
-
Save mshakhomirov/5ad1a7518c54bc030d1c78b56fe3cf82 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
create temp table last_online as ( | |
select 1 as user_id | |
, timestamp('2000-10-01 00:00:01') as last_online | |
) | |
; | |
create temp table connection_data ( | |
user_id int64 | |
,timestamp timestamp | |
) | |
PARTITION BY DATE(_PARTITIONTIME) | |
; | |
insert connection_data (user_id, timestamp) | |
select 2 as user_id | |
, timestamp_sub(current_timestamp(),interval 28 hour) as timestamp | |
union all | |
select 1 as user_id | |
, timestamp_sub(current_timestamp(),interval 28 hour) as timestamp | |
union all | |
select 1 as user_id | |
, timestamp_sub(current_timestamp(),interval 20 hour) as timestamp | |
union all | |
select 1 as user_id | |
, timestamp_sub(current_timestamp(),interval 1 hour) as timestamp | |
; | |
merge last_online t | |
using ( | |
select | |
user_id | |
, last_online | |
from | |
( | |
select | |
user_id | |
, max(timestamp) as last_online | |
from | |
connection_data | |
where | |
date(_partitiontime) >= date_sub(current_date(), interval 1 day) | |
group by | |
user_id | |
) y | |
) s | |
on t.user_id = s.user_id | |
when matched then | |
update set last_online = s.last_online, user_id = s.user_id | |
when not matched then | |
insert (last_online, user_id) values (last_online, user_id) | |
; | |
select * from last_online | |
; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment