Search code examples
sqlsql-servert-sql

In SQL, how can you "group by" in ranges?


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 range.

For example:

score range  | number of occurrences
-------------------------------------
   0-9       |        11
  10-19      |        14
  20-29      |         3
   ...       |       ...

In this example there were 11 rows with scores in the range of 0 to 9, 14 rows with scores in the range of 10 to 19, and 3 rows with scores in the range 20-29.

Is there an easy way to set this up? What do you recommend?


Solution

  • Neither of the highest voted answers are correct on SQL Server 2000. Perhaps they were using a different version.

    Here are the correct versions of both of them on SQL Server 2000.

    select t.range as [score range], count(*) as [number of occurences]
    from (
      select case  
        when score between 0 and 9 then ' 0- 9'
        when score between 10 and 19 then '10-19'
        else '20-99' end as range
      from scores) t
    group by t.range
    

    or

    select t.range as [score range], count(*) as [number of occurrences]
    from (
          select user_id,
             case when score >= 0 and score< 10 then '0-9'
             when score >= 10 and score< 20 then '10-19'
             else '20-99' end as range
         from scores) t
    group by t.range