Last active
February 7, 2024 04:01
-
-
Save hui-zheng/f4c623a19a5621f8ba23b800f4575f1d to your computer and use it in GitHub Desktop.
[BigQuery Advanced SQL] find greatest/largest/max non-null values among multiple columns
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
-- Below is a fancy version of non-null-greatest() for multi-columns. | |
-- it is more extensible for more two columns. | |
WITH base AS ( | |
SELECT | |
(SELECT ARRAY_AGG (x IGNORE NULLS) AS Y FROM UNNEST ([col_1, col_2, col_3, col_4]) AS x) | |
AS array, | |
FROM source_table AS nl | |
) | |
SELECT | |
(SELECT MAX(y) FROM UNNEST(array) AS Y | |
) AS non_null_max_value | |
FROM base | |
-- below is a simpler version for two columns | |
SELECT | |
COALESCE( | |
GREATEST(col_1,col2), | |
col1, | |
col2 | |
) | |
FROM source_table |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment