在 Postgres 中,我试图有一个按多列排序的 SQL。第一列始终是
priority DESC NULLS LAST
。第二个需要根据某些条件是动态的(为了方便举例,这里我有WHEN 1 = 1
)。
SELECT id, title, priority
FROM post
ORDER BY
priority DESC NULLS LAST,
CASE WHEN 1 = 1 THEN created_at ASC ELSE created_at DESC END;
这会引发错误:
syntax error at or near "ASC"
LINE 5: CASE WHEN 1 = 1 THEN created_at ASC ELSE created_at ...
我怎样才能在
CASE
的第二个键上有ORDER BY
?
如果 else 结束,则不能使用
DESC
或 ASC
。
尝试
SELECT id, title, priority
FROM post
ORDER BY
priority DESC NULLS LAST,
CASE WHEN 1 = 1 THEN created_at-'2025-01-01'::date -- ASC
ELSE '2025-01-01'::date-created_at END; -- DESC