在WHERE子句中使用别名

时间:2014-02-05 07:45:47

标签: sql oracle column-alias

我正在执行以下查询并为所有列使用别名。我用a命名了别名。因为这是一项要求。现在,我想直接在where子句中引用别名,我的确如下:

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%';

然而,当我执行此操作时,我收到以下错误:

    SQL Error: ORA-00904: "PT".".PRNT_PROD_ID": invalid identifier
     00904. 00000 -  "%s: invalid identifier"

我知道SQL首先执行where子句,因此这就是错误的原因。但我该如何解决这个问题呢?有什么建议吗?

3 个答案:

答案 0 :(得分:2)

您已经了解can't use the alias in the where clause,但这仅适用于相同级别的SQL。您可以将查询包装在外部查询中:

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%';

唯一的选择是重复在case子句中生成该列的整个where,这对于如此复杂的事情会很不愉快。

答案 1 :(得分:1)

将查询放在子查询中,然后可以引用where子句中的别名,例如:

SELECT * FROM (
  SELECT pt.prod_desc AS"PROD_DESC",
   ...etc...
  FROM dims_prod_type pt) pt
WHERE pt.".PRNT_PROD_ID" like 'A%';

答案 2 :(得分:0)

将“PT”。“。PRNT_PROD_ID”改为“PT”。“PRNT_PROD_ID”或通过pt.prnt_prod_id更好地理解