ORDER BY CASE WHEN ... ELSE ... END 在 PostgreSQL 中
ORDER BY CASE WHEN ... ELSE ... END in PostgreSQL
我的 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
感觉很奇怪。
如果text_column的类型是数字。你可以试试这个。
ORDER BY CASE WHEN boolean_column is true THEN text_column
ELSE -1 * text_column END ASC
你可以使用这个技巧来缩短逻辑:
ORDER BY (CASE WHEN boolean_column THEN text_column END) ASC,
text_column DESC
不过还是有两个order by
键。
可以先排序,获取每条记录的位置,然后选择排序方向
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
我的 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
感觉很奇怪。
如果text_column的类型是数字。你可以试试这个。
ORDER BY CASE WHEN boolean_column is true THEN text_column
ELSE -1 * text_column END ASC
你可以使用这个技巧来缩短逻辑:
ORDER BY (CASE WHEN boolean_column THEN text_column END) ASC,
text_column DESC
不过还是有两个order by
键。
可以先排序,获取每条记录的位置,然后选择排序方向
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