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

前端 未结 15 2188
粉色の甜心
粉色の甜心 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:39
    declare @RangeWidth int
    
    set @RangeWidth = 10
    
    select
       Floor(Score/@RangeWidth) as LowerBound,
       Floor(Score/@RangeWidth)+@RangeWidth as UpperBound,
       Count(*)
    From
       ScoreTable
    group by
       Floor(Score/@RangeWidth)
    
    0 讨论(0)
  • 2020-11-22 16:41

    Perhaps you're asking about keeping such things going...

    Of course you'll invoke a full table scan for the queries and if the table containing the scores that need to be tallied (aggregations) is large you might want a better performing solution, you can create a secondary table and use rules, such as on insert - you might look into it.

    Not all RDBMS engines have rules, though!

    0 讨论(0)
  • 2020-11-22 16:44
    create table scores (
       user_id int,
       score int
    )
    
    select t.range as [score range], count(*) as [number of occurences]
    from (
          select user_id,
             case when score >= 0 and score < 10 then '0-9'
             case when score >= 10 and score < 20 then '10-19'
             ...
             else '90-99' as range
         from scores) t
    group by t.range
    
    0 讨论(0)
提交回复
热议问题