С JOIN
и некоторым рефакторингом:
WITH range_array AS (
SELECT [400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000]
)
, buckets AS (
SELECT LAG(bucket_end) OVER(ORDER BY reputation_group) bucket_start, *
FROM UNNEST((SELECT * FROM range_array)) bucket_end WITH OFFSET reputation_group
)
SELECT *
, (SELECT AS STRUCT * FROM buckets WHERE a.reputation_group = reputation_group) bucket
FROM (
SELECT RANGE_BUCKET(reputation, (SELECT * FROM range_array)) AS reputation_group, COUNT(*) AS count
FROM `bigquery-public-data.stackoverflow.users`
WHERE reputation > 200000
GROUP BY 1
ORDER BY 1
) a
ORDER BY reputation_group
Но если вы все это делаете, про RANGE_BUCKET легче забыть:
WITH buckets AS (
SELECT IFNULL(LAG(max) OVER(ORDER BY grp), -10000000) min, *
FROM UNNEST([400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000]) max WITH OFFSET grp
)
SELECT buckets.min, buckets.max, COUNTIF(reputation >= buckets.min AND reputation < buckets.max) c
FROM `bigquery-public-data.stackoverflow.users`, buckets
WHERE reputation > 200000
GROUP BY 1,2
ORDER BY 1
Или:
SELECT IFNULL(min,0) min, max, COUNT(*) c
FROM (
SELECT (SELECT MAX(x) FROM UNNEST(ranges) x WHERE x<reputation) min, (SELECT MIN(x) FROM UNNEST(ranges) x WHERE x>reputation) max
FROM `bigquery-public-data.stackoverflow.users`
, (SELECT [400000, 500000, 600000, 700000, 800000, 900000, 1000000, 1100000, 1200000] ranges)
WHERE reputation > 200000
)
GROUP BY 1, 2
ORDER BY 1