我正在尝试在SQL中执行条件ORDER BY
但是我收到错误:column "ended" does not exist
指向"结束"''查询的一部分。
这是我的问题:
SELECT (EXTRACT(EPOCH FROM SUBMISSION_DEADLINE)
-EXTRACT(EPOCH FROM now())) AS "datediff"
, (EXTRACT(EPOCH FROM SUBMISSION_DEADLINE)>EXTRACT(EPOCH FROM now())) AS "ended", *
FROM imdown_api_v1_contest
ORDER BY "ended" DESC, case when "ended" = true then "datediff" else "-datediff" END ASC;
我需要先抓住尚未结束的比赛,然后先按顺序结束。然后我需要所有已经结束的东西,并按最近结束的那些顺序排序。
答案 0 :(得分:2)
列ended
,sql按下一顺序执行查询:
因此,您需要将完整表达式复制到order by
子句中或使用子查询,例如:
select * from (
SELECT (EXTRACT(EPOCH FROM SUBMISSION_DEADLINE)-EXTRACT(EPOCH FROM now())) AS "datediff", (EXTRACT(EPOCH FROM SUBMISSION_DEADLINE)>EXTRACT(EPOCH FROM now())) AS "ended", *
FROM imdown_api_v1_contest
) tmpq
ORDER BY "ended" DESC, case when "ended" = true then "datediff" else "-datediff" END ASC
答案 1 :(得分:1)
您的查询在多个位置被破坏或效率低下,而不仅仅是对列别名的非法引用。这可能符合你的意图:
SELECT EXTRACT(EPOCH FROM now() - submission_deadline) AS datediff
, now() > submission_deadline AS ended -- I inverted your expression!
, *
FROM imdown_api_v1_contest
ORDER BY 2 -- positional reference to output column
, @(EXTRACT(EPOCH FROM now() - submission_deadline))
通常,竞赛结束"在 过去 中有submission_deadline
,所以now() > submission_deadline AS ended
,而不是相反。
要修复主要语法错误,我使用位置引用而不是列别名。详细解释:
相关示例:
要获得所需的订单,请使用absolute value operator @
。