sql - group by in ranges to include ranges without values

后端 未结 4 766
生来不讨喜
生来不讨喜 2021-02-13 17:45

Suppose a scenario similar to this question. I want to get the following results:

score range  | number of occurrences
-------------------------------------
   0         


        
4条回答
  •  执念已碎
    2021-02-13 17:53

    Actually, the simplest solution is this (for 2 digit numbers):

    select substr(rssi::text, 0, 2) || '0-' || substr(rssi::text, 0, 2) || '9' as range, count(*)
    from sensor_stations
    group by substr(rssi::text, 0, 2)
    order by count(*) desc;
    

    The output will be something like this:

     range | count 
    -------+-------
     10-19 |  3414
     30-39 |  1363
     20-29 |  1269
     40-49 |   769
     50-59 |   294
     60-69 |   106
     70-79 |     5
    (7 rows)
    

提交回复
热议问题