I have a SQL query like this:
select age_group, sum(member_count), sum(discharge_count)
from newtable
group by age_group
order by age_group;
It is returns these results:
age_group | member_count | discharge_count |
---|---|---|
18-64 Years | 150 | 245 |
6-17 Years | 185 | 325 |
65 and Above Years | 125 | 230 |
But I want results like this instead:
age_group | member_count | discharge_count |
---|---|---|
6-17 Years | 185 | 325 |
18-64 Years | 150 | 245 |
65 and Above Years | 125 | 230 |
2
Answers
String ordering doesn’t know numbers, so what happened is that, first it compares the first letter, then the second and so on. And since the letter "6" comes after "1" in the alphabet, your results get messed up. You should extract the numbers at the beginning of the
age_group
field (with twoSPLIT_PART
s) and convert them to numeric type (withCAST
):You can substring the value until the position – and sort the result,