Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split rows in limited size buckets

I have a table with thousands of records, I want to associate each row with a bucket and each bucket has a maximum of rows associated to it.

I'd love something a "bucketize" analytic function similar to ntile but that instead of the number of buckets takes the maximum number of elements of each bucket.

Is there anything like that?

select value, bucketize(3) as bucket
  from table;

VALUE   BUCKET
--------------
foo          1
bar          1
baz          1
qux          2
quux         2
zap          2
xfoo         3
xbar         3
xbaz         3
xqux         4
like image 680
molok Avatar asked Jan 19 '26 19:01

molok


1 Answers

You can just use row_number():

select value, floor((row_number() over (order by value) - 1) / 3) as bucket
from t;

I don't think a separate window function is really needed in this case.

like image 200
Gordon Linoff Avatar answered Jan 21 '26 08:01

Gordon Linoff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!