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
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,...)
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.
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.
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.
SELECT *
FROM mytable
ORDER BY
GREATEST(pc_1, pc_2) DESC, LEAST(pc_1, pc_2) DESC
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