ORDER BY PostgreSQL中的复杂表达式

时间:2015-09-11 14:13:58

标签: postgresql sorting

我正在尝试ORDER BY两个double值(别名列)之间的差异,但它没有看到别名列。

示例:

SELECT COALESCE(
  ROUND(
   SUM(amount * currency1.rate / currency2.rate)
   , 4)
 , 0) AS first_amount,
SUM(
   (SELECT
     COALESCE(
       ROUND(
         SUM(table2.amount * currency3.rate / currency2.rate)
       , 4)
     , 0)
   FROM table2
     JOIN currencies currency3
       ON currency3.id = table2.currency_id
   WHERE table2.date BETWEEN table1.start_date AND table1.end_date
   )
 ) AS second_amount
 FROM table1
 JOIN currencies currency1
   ON currency3.id = table1.currency_id
 JOIN currencies currency2
   ON currency3.id = 123  # some hardcoded ID
 ORDER BY first_amount - second_amount ASC

Postgres告诉我,first_amount列不存在。 阅读文档,我看到Postgres 9.0不允许带有别名列的表达式。

如何通过以正确的方式对所需的所有内容进行排序来解决问题?

1 个答案:

答案 0 :(得分:5)

列别名不能直接在where或order by子句中使用。您需要将它包装在派生表中。

select *
from (
  ... your original query goes here ...
) as t
ORDER BY first_amount - second_amount ASC;