I have table in SQL Server which contains a column of type "int". The column can contain positive as well as negative values. I want to carry out sorting based on this column values such that rows with positive values in this column come before the negative values.
Example:
Code SortColumn
A 1
B 5
C -1
D -3
E 0
F 2
Desired Output:
Code SortColumn
E 0
A 1
F 2
B 5
C -3
D -1
The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.
We can convert Negative amount to Positive Amount using ABS() function.
If you want to select records from a table but would like to see them sorted according to two columns, you can do so with ORDER BY . This clause comes at the end of your SQL query.
No, that order doesn't matter (or at least: shouldn't matter). Any decent query optimizer will look at all the parts of the WHERE clause and figure out the most efficient way to satisfy that query.
Select * from Table
order by
Case when sortcolumn<0 then 1 else 0 end
,sortcolumn
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With