In SQL, how can you “group by” in ranges?

前端 未结 15 2496
粉色の甜心
粉色の甜心 2020-11-22 15:38

Suppose I have a table with a numeric column (lets call it \"score\").

I\'d like to generate a table of counts, that shows how many times scores appeared in each ran

15条回答
  •  生来不讨喜
    2020-11-22 16:36

    In postgres (where || is the string concatenation operator):

    select (score/10)*10 || '-' || (score/10)*10+9 as scorerange, count(*)
    from scores
    group by score/10
    order by 1
    

    gives:

     scorerange | count 
    ------------+-------
     0-9        |    11
     10-19      |    14
     20-29      |     3
     30-39      |     2
    

提交回复
热议问题