SQL order by highest value of two columns

I have a PostgreSQL table with some doubling, they store precentages. so let's say the columns are:

pc_1 pc_2 

What I want is to sort by which of these two columns has the largest number of descending ones, and then the other column descends again.

So, if our data is, let's say:

 id pc_1 pc_2 1 12.5 11.0 2 10.0 13.2 3 13.2 9.0 

select * from my tabular order at <something >:

  2 10.0 13.2 3 13.2 9.0 1 12.5 11.0 
+6
source share
2 answers
 SELECT * FROM mytable ORDER BY GREATEST(pc_1, pc_2) DESC, LEAST(pc_1, pc_2) DESC 
+16
source
 select * from mytable order by case when pc_1 > pc_2 then pc_1 else pc_2 end desc, case when pc_1 > pc_2 then pc_2 else pc_1 end desc 
+4
source

Source: https://habr.com/ru/post/917650/


All Articles