为什么我得到专栏"结束"不存在?

时间:2015-11-03 23:06:47

标签: sql postgresql sql-order-by

我正在尝试在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;

我需要先抓住尚未结束的比赛,然后先按顺序结束。然后我需要所有已经结束的东西,并按最近结束的那些顺序排序。

2 个答案:

答案 0 :(得分:2)

执行order by时,未定义

ended,sql按下一顺序执行查询:

  1. ,其中
  2. 顺序
  3. 选择
  4. 因此,您需要将完整表达式复制到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 @