ORA-00904 invalid identifier on decode alias

痞子三分冷 提交于 2019-11-28 14:12:24

From the documentation (emphasis added):

You can use a column alias, c_alias, to label the immediately preceding expression in the select list so that the column is displayed with a new heading. The alias effectively renames the select list item for the duration of the query. The alias can be used in the ORDER BY clause, but not other clauses in the query.

So you can't refer to the alias in the where clause, where at the moment you have:

...
AND (account_amt NOT BETWEEN ...
...

The alias isn't valid at that point, so it's looking for a column with that name in one of the tables, and doesn't find one. It's fine in the order by though.

You either need to replace the alias with the repeated decode statement, or possibly use a subquery and then refer to the alias in a where clause in an outer query, but that might end up being less efficient depending on how selective your other conditions are.

Oracle runs the select query in the order below:

  1. FROM clause
  2. WHERE clause
  3. GROUP BY clause
  4. HAVING clause
  5. SELECT clause
  6. ORDER BY clause

Based on the above, you can see that when you are in the WHERE part, the alias has not yet been created. If you would like to use results from the SELECT part, you can do that by modifying your query like this:

WITH q AS 
(
-- Your query without the extra AND
)
SELECT *
FROM q
WHERE --put your check here

This way you will already have the alias available when you reach the WHERE part.

Hope this helps! :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!