Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL order by absolute values

I have some data in my table below

table_1
     column_1     column_2
        1           10
        1           20
        1           30
        1           40
        1           50
        2           -10
        2           -20
        2           -30
        2           -40
        2           -50

I want to change this result to something like this

 column_1     column_2
    1           10
    2           -10
    1           20
    2           -20
    1           30
    2           -30
    1           40
    2           -40
    1           50
    2           -50

I am not sure if there is a way to do this using order by? What I am trying to show is I am trying to show (10,-10) as a group of data

like image 578
RedRocket Avatar asked Jun 23 '16 11:06

RedRocket


3 Answers

You can simply use ABS() function, that returns the absolute value of a number :

SELECT * FROM YourTable
ORDER BY ABS(Column_2),column_2 desc

This query will be ordered by the absolute value of Column_2

like image 165
sagi Avatar answered Oct 17 '22 03:10

sagi


SELECT * 
FROM <table>
ORDER BY abs(column_2), column_2 desc
like image 32
t-clausen.dk Avatar answered Oct 17 '22 02:10

t-clausen.dk


Looks like you want to sort on the absolute value of the second column, then the first column.

select column_1, column_2 from table_1 order by abs(column_2),column_1
like image 27
alroc Avatar answered Oct 17 '22 01:10

alroc