如何在SQL

时间:2016-10-08 12:10:01

标签: sql oracle oracle11g

SELECT E.EMPNO,E.DEPTNO,E.SAL,E.COMM,
COALESCE(SAL,0)+COALESCE(COMM,0) AS T1,
CASE
WHEN E.DEPTNO=10 THEN COALESCE(E.SAL,0)+COALESCE(E.COMM,0)
WHEN D.DNAME='ACCOUNTING' THEN COALESCE(E.SAL,0)-COALESCE(E.COMM,0)
ELSE 0 END AS T,
sum(T+T1) as T2

FROM EMP E LEFT OUTER JOIN DEPT D ON E.DEPTNO=D.DEPTNO;

低于错误:

  

ORA-00904:" T1":无效的标识符   00904. 00000 - "%s:无效标识符"   *原因:
  *动作:行错误:7列:7

1 个答案:

答案 0 :(得分:0)

您不能使用select子句中定义的别名,并在同一select子句中的其他位置引用它们。

这意味着sum(T+T1)无效,因为T并且T1无法被识别。

一种解决方法是将您的查询移到派生表中,然后您可以在外部查询中引用TT1

SELECT x.*,
       sum(x.T+x.T1) as T2
  FROM (SELECT E.EMPNO,
               E.DEPTNO,
               E.SAL,
               E.COMM,
               COALESCE(SAL,0)+COALESCE(COMM,0) AS T1,
               CASE
                 WHEN E.DEPTNO=10 THEN COALESCE(E.SAL,0)+COALESCE(E.COMM,0)
                 WHEN D.DNAME='ACCOUNTING' THEN COALESCE(E.SAL,0)-COALESCE(E.COMM,0)
                 ELSE 0 
               END AS T,
          FROM EMP E 
          LEFT OUTER JOIN DEPT D 
            ON E.DEPTNO=D.DEPTNO) x