'How to sort one column and then another within it in SQL? [duplicate]
I have this table
state num
-------------------------
ca 20
ny 30
ca 50
ca 10
ny 70
ny 90
What I want is to produce this:
state num
-------------------------
ca 50
ca 20
ca 10
ny 90
ny 70
ny 30
Basically, I want the state column to be sorted, and then within each state, have the num sorted as well. How can I achieve this?
Solution 1:[1]
specify both column you want to sort one separated by a comma :
select state, num from table_name order by 1, 2 desc
or
select state, num from table_name order by state, num desc
(seems like you wanted the first column sorted on asc
way while the second one in desc
way)
Solution 2:[2]
SELECT * FROM yourtablename ORDER BY state, num DESC
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Thierry |
Solution 2 | andrea margotti |