WIDTH_BUCKET Equal Width Histogram

Bucket amounts into equal-width ranges with WIDTH_BUCKET, which keeps out-of-range values in buckets 0 and n+1 rather than dropping them.

SqlData Fetching

Code

snippet
-- WIDTH_BUCKET(amount, 0, 200, 4) 把 [0, 200) 等宽切成 4 个桶:
-- 低于 0 进 0 号桶,200 及以上进 5 号桶(n+1),不会丢弃任何一行
SELECT
    WIDTH_BUCKET(amount, 0, 200, 4) AS bucket,
    MIN(amount) AS bucket_min,
    MAX(amount) AS bucket_max,
    COUNT(*)    AS orders
FROM orders
GROUP BY bucket
ORDER BY bucket;

-- 与 NTILE 的区别:NTILE 按行数等分(每桶行数接近、区间宽度不等),
-- WIDTH_BUCKET 按取值区间等分(每桶宽度相同、行数可以悬殊)
SELECT
    NTILE(4) OVER (ORDER BY amount) AS ntile_bucket,
    WIDTH_BUCKET(amount, 0, 200, 4) AS width_bucket
FROM orders;

Inside the snippet

What runs here is SELECT — orders are the objects involved.

What the statements actually assemble: COUNT, MIN, MAX aggregation; a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) computing values across rows without collapsing them; an ORDER BY that fixes the output order.

What to watch for

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Putting it to use

The orders table is the working surface here.

Core lines

SELECT
    WIDTH_BUCKET(amount, 0, 200, 4) AS bucket,
    MIN(amount) AS bucket_min,
    MAX(amount) AS bucket_max,
    COUNT(*)    AS orders
FROM orders
GROUP BY bucket
ORDER BY bucket;
SELECT
    NTILE(4) OVER (ORDER BY amount) AS ntile_bucket,
    WIDTH_BUCKET(amount, 0, 200, 4) AS width_bucket
FROM orders;

Interactive Tools for This Topic

FAQ

Which tables or CTEs does it reference?
`orders`.