【问题标题】:SQL: Order by - sorting on another column in case of tieSQL:排序方式 - 在出现平局的情况下对另一列进行排序
【发布时间】:2016-11-11 19:56:35
【问题描述】:

我的示例表

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; 

-

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

任何帮助将不胜感激。谢谢!

【问题讨论】:

    标签: sql postgresql sql-order-by


    【解决方案1】:
    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 时,它将参与升序订购。

    【讨论】:

    • 谢谢!这就像一个魅力。我不知道你可以这样嵌套案例,学到了一些新东西。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-16
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      相关资源
      最近更新 更多