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

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

    Because the column being sorted on (Range) is a string, string/word sorting is used instead of numeric sorting.

    As long as the strings have zeros to pad out the number lengths the sorting should still be semantically correct:

    SELECT t.range AS ScoreRange,
           COUNT(*) AS NumberOfOccurrences
      FROM (SELECT CASE
                        WHEN score BETWEEN 0 AND 9 THEN '00-09'
                        WHEN score BETWEEN 10 AND 19 THEN '10-19'
                        ELSE '20-99'
                   END AS Range
              FROM Scores) t
     GROUP BY t.Range
    

    If the range is mixed, simply pad an extra zero:

    SELECT t.range AS ScoreRange,
           COUNT(*) AS NumberOfOccurrences
      FROM (SELECT CASE
                        WHEN score BETWEEN 0 AND 9 THEN '000-009'
                        WHEN score BETWEEN 10 AND 19 THEN '010-019'
                        WHEN score BETWEEN 20 AND 99 THEN '020-099'
                        ELSE '100-999'
                   END AS Range
              FROM Scores) t
     GROUP BY t.Range
    

提交回复
热议问题