I'm looking to replicate the width_bucket function that is available in Oracle with a new function in BigQuery. The function creates equiwidth buckets based on the number you specify between a min and max value. For example, width_bucket(user_count, 0, 35, 10) would create 10 equal buckets like 0 - 3.5, 3.5 - 7, etc and tell you which bucket user_count falls in. Any assistance would be greatly appreciated!
Oracle doc - https://docs.oracle.com/cd/B19306_01/server.102/b14200/functions214.htm
Here's what I have and I believe this works, but I want to get it so I don't have to reference a table if possible to generate the row numbers.
CREATE OR REPLACE FUNCTION functions.widthBucket(
value NUMERIC,
minValue NUMERIC,
maxValue NUMERIC,
buckets INT64)
AS ((
SELECT resultBucket
FROM (
SELECT CASE
WHEN value >= (minValue * bucketNumber) + ((maxValue/buckets) * (bucketNumber - 1))
AND value < (maxValue/buckets) * bucketNumber
THEN bucketNumber
WHEN value = maxValue and bucketNumber = buckets
THEN bucketNumber
ELSE -1
END as resultBucket
FROM (
SELECT ROW_NUMBER() OVER (PARTITION BY '') as bucketNumber
FROM project.dateTable
) x
WHERE bucketNumber <= buckets) x
WHERE resultBucket != -1
));