Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL order by highest value of two columns

Tags:

sql

postgresql

I have a PostgreSQL table with some doubles, they store precentages. so let's say the columns are pc_1 and pc_2.

What I want is to order by whichever of these two columns has the highest amount descending, and then by the other column, again descending.

So if our data is as follows:

id  pc_1  pc_2 
 1  12.5  11.0
 2  10.0  13.2
 3  13.2  9.0
select * from mytable order by <something>

Would give:

 2  10.0  13.2
 3  13.2  9.0
 1  12.5  11.0
like image 844
Tom Carrick Avatar asked Jun 08 '12 17:06

Tom Carrick


People also ask

How do I find the maximum value of two columns in SQL?

The MySQL Solution If you're working with MySQL, you can combine MAX() with the GREATEST() function to get the biggest value from two or more fields. Here's the syntax for GREATEST: GREATEST(value1,value2,...)

Can we use ORDER BY for 2 columns?

You can also ORDER BY two or more columns, which creates a nested sort . The default is still ascending, and the column that is listed first in the ORDER BY clause takes precedence. The following query and Figure 3 and the corresponding query results show nested sorts.

What is ORDER BY 2 desc in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.24-Aug-2022.

How do I sort multiple columns in ascending order in SQL?

Syntax: SELECT * FROM table_name ORDER BY column_name; For Multiple column order, add the name of the column by which you'd like to sort records first. The column that is entered at first place will get sorted first and likewise.


1 Answers

SELECT  *
FROM    mytable
ORDER BY
        GREATEST(pc_1, pc_2) DESC, LEAST(pc_1, pc_2) DESC
like image 146
Quassnoi Avatar answered Oct 16 '22 14:10

Quassnoi