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

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

    James Curran's answer was the most concise in my opinion, but the output wasn't correct. For SQL Server the simplest statement is as follows:

    SELECT 
        [score range] = CAST((Score/10)*10 AS VARCHAR) + ' - ' + CAST((Score/10)*10+9 AS VARCHAR), 
        [number of occurrences] = COUNT(*)
    FROM #Scores
    GROUP BY Score/10
    ORDER BY Score/10
    

    This assumes a #Scores temporary table I used to test it, I just populated 100 rows with random number between 0 and 99.

提交回复
热议问题