问题
I am executing the below query and using alias name for all columns. I have named alias with a . since that is a requirement. now, I want to refer to the alias name directly in the where clause and i do is as given below:
SELECT pt.prod_desc AS"PROD_DESC",
(
CASE
WHEN pt.prod_level='2'
THEN 'Product'
WHEN pt.prod_level='4'
THEN 'Sub-Product'
WHEN pt.prod_level='5'
THEN 'Service'
ELSE 'N/A'
END) AS"PROD_LEVEL",
prod_id AS "PROD_ID",
isactive AS "IsActive",
updt_usr_sid AS "UPDT_USR_SID",
updt_ts AS "UPDT_TS",
(
CASE
WHEN pt.prod_level='5'
THEN parent_prod_id
ELSE NULL
END) AS ".SUB_PROD_ID",
(
CASE
WHEN pt.prod_level='5'
THEN
(SELECT prod_desc FROM dims_prod_type A WHERE A.prod_id= pt.parent_prod_id
)
ELSE 'N/A'
END ) AS ".SUB_PROD_DESC",
(
CASE
WHEN pt.prod_level='4'
THEN parent_prod_id
WHEN pt.prod_level='5'
THEN
(SELECT parent_prod_id
FROM dims_prod_type A
WHERE A.prod_id= pt.parent_prod_id
)
ELSE NULL
END) AS ".PRNT_PROD_ID",
(
CASE
WHEN pt.prod_level='4'
THEN
(SELECT prod_desc FROM dims_prod_type A WHERE A.prod_id=pt.parent_prod_id
)
WHEN pt.prod_level='5'
THEN
(SELECT prod_desc
FROM dims_prod_type A
WHERE A.prod_id IN
(SELECT B.parent_prod_id
FROM dims_prod_type B
WHERE b.prod_id=pt.parent_prod_id
)
)
ELSE 'N/A'
END)AS ".PRNT_PROD_DESC"
FROM dims_prod_type pt
WHERE pt.".PRNT_PROD_ID" like 'A%';
However when i am executing this I get the following error:
SQL Error: ORA-00904: "PT".".PRNT_PROD_ID": invalid identifier
00904. 00000 - "%s: invalid identifier"
I know that SQL executes the where clause first and hence that is the reason of the error. But how do i fix this? Any suggestions please?
回答1:
You already know you can't use the alias in the where clause, but that only applies in the same level of SQL. You can wrap your query in an outer query:
SELECT *
FROM (
SELECT pt.prod_desc AS"PROD_DESC",
...
END)AS ".PRNT_PROD_DESC"
FROM dims_prod_type pt
)
WHERE ".PRNT_PROD_ID" like 'A%';
The only alternative would be to repeat the whole case
that generates that column in the where
clause, which would be unpleasant with something so complicated.
回答2:
Put the query in a subquery, then you can refer to the aliases in your where clause, e.g.:
SELECT * FROM (
SELECT pt.prod_desc AS"PROD_DESC",
...etc...
FROM dims_prod_type pt) pt
WHERE pt.".PRNT_PROD_ID" like 'A%';
回答3:
Replace "PT".".PRNT_PROD_ID" by "PT"."PRNT_PROD_ID" or for a better understanding by pt.prnt_prod_id
来源:https://stackoverflow.com/questions/21571426/using-alias-name-in-where-clause