【问题标题】:ORDER BY CASE WHEN ... ELSE ... END in PostgreSQLORDER BY CASE WHEN ... ELSE ... END 在 PostgreSQL
【发布时间】:2018-03-03 19:31:43
【问题描述】:

我的ORDER BY 子句如下:

...
ORDER BY CASE WHEN boolean_column is true  THEN text_column END ASC,
         CASE WHEN boolean_column is false THEN text_column END DESC

是否有可能以某种方式替换ELSE 中的第二个CASE?有两个条件而不是通常的if else/when else 感觉很奇怪。

【问题讨论】:

  • 不太简单——因为你在第一种情况下使用升序,在其他情况下使用降序

标签: sql postgresql sql-order-by


【解决方案1】:

你可以使用这个技巧来缩短逻辑:

ORDER BY (CASE WHEN boolean_column THEN text_column END) ASC,
         text_column DESC

它仍然是两个 order by 键。

【讨论】:

    【解决方案2】:

    如果 text_column 的类型是数字。你可以试试这个。

    ORDER BY CASE WHEN boolean_column is true THEN text_column 
                  ELSE -1 * text_column END ASC
    

    【讨论】:

      【解决方案3】:

      你可以先排序,得到每条记录的位置,然后选择排序方向

      WITH rows_with_positions AS (
          SELECT
              boolean_column,
              text_column,
              ROW_NUMBER() OVER (ORDER BY text_column) AS position,
              .. 
          FROM your_table
      )
      SELECT text_column, ..
      FROM rows_with_positions
      ORDER BY
          CASE WHEN boolean_column
              THEN position
              ELSE -1 * position
              END
          ASC
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-03-27
        • 1970-01-01
        • 2014-09-14
        • 1970-01-01
        • 1970-01-01
        • 2017-04-10
        • 1970-01-01
        相关资源
        最近更新 更多