Last active
July 26, 2020 15:20
-
-
Save kyontan/d160bbaca44b0cbfc413f3a7e8ce8439 to your computer and use it in GitHub Desktop.
BigQuery MERGE DML to merge {source} into {destination} with having same primary keys also having newer updated_at
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
MERGE {destination} T | |
USING ( | |
SELECT * EXCEPT(rn) | |
FROM ( | |
SELECT | |
*, | |
row_number() over (PARTITION BY {primary_keys} ORDER BY updated_at DESC) AS rn | |
FROM {source}) | |
WHERE rn = 1 | |
) S | |
ON T.{primary_key1} = S.{primary_key1} AND ... | |
WHEN MATCHED AND T.updated_at < S.updated_at THEN | |
UPDATE SET {col1} = S.{col1}, ... | |
WHEN NOT MATCHED THEN | |
INSERT (col1, ...) VALUES (col1, ...) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment