SQL: 排序依据 - 如果出现平局则在另一列上排序

SQL: Order by - sorting on another column in case of tie

我的样本table

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的降序排序。

所以我的结果 table 应该是这样的:

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|      |  

我的查询有问题。我已尝试执行以下操作,但其中 none 似乎工作正常。

/* 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; 

-

/* When this finds a null value, it basically ignores the desc requirement of col 2 */
select *
from table
order by
    col1 desc nulls last,
    id asc,
    col2 desc nulls last; 

如果重要的话,我正在使用 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 排序后,您希望根据 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;