SQL顺序由两列的最高值组成

时间:2022-09-18 13:39:58

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

我有一个带有一些双打的PostgreSQL表,它们存储了前置数。所以让我们说列是:

pc_1
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, say:

所以,如果我们的数据是,请说:

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:

通过 从mytable订单中选择*会给出:

 2  10.0  13.2
 3  13.2  9.0
 1  12.5  11.0

2 个解决方案

#1


18  

SELECT  *
FROM    mytable
ORDER BY
        GREATEST(pc_1, pc_2) DESC, LEAST(pc_1, pc_2) DESC

#2


4  

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

#1


18  

SELECT  *
FROM    mytable
ORDER BY
        GREATEST(pc_1, pc_2) DESC, LEAST(pc_1, pc_2) DESC

#2


4  

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