PostgreSQL, Aggregates and Histograms

Let’s have a look at our dataset from the NBA games and statistics, and get back to counting rebounds in the drb field. A preliminary query informs us that we have stats ranging from 10 to 54 rebounds per team in a single game, a good information we can use in the following query:

  <span class="keyword">select</span> width_bucket(drb, <span class="number">10</span>, <span class="number">54</span>, <span class="number">9</span>) <span class="keyword">as</span> buckets,
         <span class="keyword">count</span>(*)
    <span class="keyword">from</span> team_stats
<span class="keyword">group</span> <span class="keyword">by</span> buckets
<span class="keyword">order</span> <span class="keyword">by</span> buckets;

We asked for 9 separations so we have 10 groups as a result:

 width_bucket | count 
--------------+-------
            1 |    52
            2 |  1363
            3 |  8832
            4 | 20917
            5 | 20681
            6 |  9166
            7 |  2093
            8 |   247
            9 |    20
           10 |     1
(10 rows)