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?
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:
If the range is mixed, simply pad an extra zero:
I see answers here that won't work in SQL Server's syntax. I would use:
EDIT: see comments
I would do this a little differently so that it scales without having to define every case:
Not tested, but you get the idea...
In postgres (where
||
is the string concatenation operator):gives:
Make sure you use a word other than 'range' if you are in MySQL, or you will get an error for running the above example.