Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

redshift SQL - Histogram With Equal Width Bins

I currently have table like so:

ID Count Value
1 45
2 24
3 13
4 67
5 3
6 21
... ...

Anyone know how to create a table that I can use to create a histogram with equal width bins going from min to max?

End result would look something like this:

Bin of Values Count(of IDs)
min-5 3
6-10 20
11-15 5
16-20 2
21-25 35
... ...
(max-5)-max 1

I have used width_bucket in the past, but Redshift does not support the function. Any help would be greatly appreciated. Thank you!

like image 673
John Avatar asked Mar 18 '26 19:03

John


1 Answers

You can use case in Redshift. It's a bit more laborious than width_bucket but the results can be the same:

select
    case
        when val between 0 and 5
            then '0-5'
        when val between 5 and 10
            then '5-10'
        when val between 10 and 15
            then '10-15'
        when val between 15 and 20
            then '15-20'
        ...
        end,
    count(1)
from my_table
group by 1;
like image 199
Carasel Avatar answered Mar 21 '26 08:03

Carasel