SQL:如果是平局,则按另一列排序
我的样本表SQL:如果是平局,则按另一列排序,sql,postgresql,sql-order-by,Sql,Postgresql,Sql Order By,我的样本表 id | col1 | col2 ---+------+----- 1 | 5 | 1 11| | 8 | 1 | 2 3 | | 1 4 | 1 | (where blanks are nulls) 6 | | 4 2 | 4 | 9 9 | 7 | 10| | 我试图按col1降序排序(最后为空),如果是平局(例如,行(8,1,2)和(4,1,),我希望按id升
id | col1 | col2
---+------+-----
1 | 5 | 1
11| |
8 | 1 | 2
3 | | 1
4 | 1 | (where blanks are nulls)
6 | | 4
2 | 4 | 9
9 | 7 |
10| |
我试图按col1降序排序(最后为空),如果是平局(例如,行(8,1,2)和(4,1,),我希望按id升序排序
如果col1中的剩余值为null,那么我将按col2的降序进行排序
因此,我的结果表应该如下所示:
id | col1 | col2
---+------+-----
9 | 7 |
1 | 5 | 1
2 | 4 | 9
4 | 1 | (where blanks are nulls)
8 | 1 | 2
6 | | 4
3 | | 1
10| |
11| |
我的询问有问题。我试过做下面的事情,但似乎没有一个能正常工作
/* This creates the correct ordering, but in the case of ties
they are ignored and don't follow id ascending */
select *
from table
order by
col1 desc nulls last,
col2 desc nulls last,
id asc;
-
如果重要的话,我正在使用PostgreSQL
任何帮助都将不胜感激。谢谢
SELECT *
FROM
Table
ORDER BY
Col1 DESC nulls last,
,CASE WHEN Col1 IS NOT NULL THEN Id END ASC
,Col2 DESC nulls last
,Id
诀窍是在Col1为null时使用case表达式删除ID值,因此当您按它排序时,它将对Col1为null的所有ID进行相同的处理,但当Col1不为null时,它将按升序参与排序
诀窍是当Col1为null时,使用大小写表达式删除ID值,因此当您按它排序时,它将对Col1为null的所有ID进行相同的处理,但当Col1不为null时,它将按升序进行排序。按Col1排序后,您希望根据Col1中的内容按ID或col2排序。由于在一种情况下是升序,在另一种情况下是降序,因此可以使用减号:
select *
from table
order by
col1 desc nulls last,
case when col1 is null then col2 else -id end desc nulls last;
按col1排序后,您希望根据col1中的内容按id或col2排序。由于在一种情况下是升序,在另一种情况下是降序,因此可以使用减号:
select *
from table
order by
col1 desc nulls last,
case when col1 is null then col2 else -id end desc nulls last;
非常感谢。这很有魅力。我不知道你能在这样的情况下,学到一些新的东西。谢谢!这很有魅力。我不知道你能把这样的案子套进去,学到一些新东西。