percentiles(arr, percentile)
Finds the specified <percentile> of an array <arr>.
CREATE OR REPLACE FUNCTION `justfunctions.eu.percentiles`(`arr` array<float64>, `percentile` int)
RETURNS float64 AS ((
SELECT
COALESCE(arr[SAFE_OFFSET(CAST(ARRAY_LENGTH(arr)*percentile/100 AS INT)-1)],COALESCE(arr[SAFE_OFFSET (0)],999))
FROM (SELECT ARRAY_AGG(x IGNORE NULLS ORDER BY x) AS arr FROM UNNEST(arr) AS x)
)
)
OPTIONS ( description = '''Finds the specified <percentile> of an array <arr>.''')
Example
SELECT `justfunctions.eu.percentiles`([1.2, 2.3, 3.2, 4.2, 5], 50)
3.2