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

前端 未结 15 2434
粉色の甜心
粉色の甜心 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:31

    An alternative approach would involve storing the ranges in a table, instead of embedding them in the query. You would end up with a table, call it Ranges, that looks like this:

    LowerLimit   UpperLimit   Range 
    0              9          '0-9'
    10            19          '10-19'
    20            29          '20-29'
    30            39          '30-39'
    

    And a query that looks like this:

    Select
       Range as [Score Range],
       Count(*) as [Number of Occurences]
    from
       Ranges r inner join Scores s on s.Score between r.LowerLimit and r.UpperLimit
    group by Range
    

    This does mean setting up a table, but it would be easy to maintain when the desired ranges change. No code changes necessary!

提交回复
热议问题