我只是SQL的初学者,但我遇到了这个恼人的错误。 SQL遇到此脚本的WHERE子句的问题:
SELECT
ITEM_ID, ITEM_PRICE, DISCOUNT_AMOUNT, QUANTITY,
(ITEM_PRICE*QUANTITY) AS price_total,
(DISCOUNT_AMOUNT*QUANTITY) AS discount_total,
((ITEM_PRICE-DISCOUNT_AMOUNT)*QUANTITY) AS item_total
FROM ORDER_ITEMS
WHERE item_total > 500
ORDER BY item_total;
我收到此错误:
Error starting at line : 1 in command -
SELECT
ITEM_ID, ITEM_PRICE, DISCOUNT_AMOUNT, QUANTITY,
(ITEM_PRICE*QUANTITY) AS price_total,
(DISCOUNT_AMOUNT*QUANTITY) AS discount_total,
((ITEM_PRICE-DISCOUNT_AMOUNT)*QUANTITY) AS item_total
FROM ORDER_ITEMS
WHERE item_total > 500
ORDER BY item_total DESC;
Error at Command Line : 7 Column : 7
Error report -
SQL Error: ORA-00904: "ITEM_TOTAL": invalid identifier
00904. 00000 - "%s: invalid identifier"
*Cause:
*Action:
我不知道为什么它与price_total和discount_total没有问题,但是报告item_total无效。我试图在减去折扣金额时首先仅选择总数大于500的项目,并将其乘以数量。然后,我需要按item_total
按降序对结果进行排序答案 0 :(得分:13)
可以在查询选择列表中使用别名为列提供不同的名称。您可以在GROUP BY,ORDER BY或HAVING中使用别名 条款引用该栏目。
标准SQL不允许在WHERE子句中引用列别名。强制执行此限制是因为WHERE子句是 评估后,列值可能尚未确定。
因此,以下查询是非法的:
SQL> SELECT empno AS employee, deptno AS department, sal AS salary
2 FROM emp
3 WHERE employee = 7369;
WHERE employee = 7369
*
ERROR at line 3:
ORA-00904: "EMPLOYEE": invalid identifier
SQL>
列别名在:
中允许在以下情况下,您可以参考WHERE子句中的列别名:
例如,
SQL> SELECT * FROM
2 (
3 SELECT empno AS employee, deptno AS department, sal AS salary
4 FROM emp
5 )
6 WHERE employee = 7369;
EMPLOYEE DEPARTMENT SALARY
---------- ---------- ----------
7369 20 800
SQL> WITH DATA AS(
2 SELECT empno AS employee, deptno AS department, sal AS salary
3 FROM emp
4 )
5 SELECT * FROM DATA
6 WHERE employee = 7369;
EMPLOYEE DEPARTMENT SALARY
---------- ---------- ----------
7369 20 800
SQL>
答案 1 :(得分:0)
您不能使用在查询
中用作别名的列名原因:
当时查询将首先检查运行时是否在表“ORDER_ITEMS”中找不到列名“item_total”,因为它是作为别名提供的,它不存储在任何地方,并且您只在所需的输出中分配该列
替代:
如果你想使用那种类型,请使用子查询,它的性能不好但是它是另一种方式
SELECT * FROM
(SELECT
ITEM_ID, ITEM_PRICE, DISCOUNT_AMOUNT, QUANTITY,
(ITEM_PRICE*QUANTITY) AS price_total,
(DISCOUNT_AMOUNT*QUANTITY) AS discount_total,
((ITEM_PRICE-DISCOUNT_AMOUNT)*QUANTITY) AS item_total
FROM ORDER_ITEMS) as tbl
WHERE tbl.item_total > 500
ORDER BY tbl.item_total;
答案 2 :(得分:0)
从Oracle 12c开始,您可以使用CROSS APPLY
定义表达式,然后可以在WHERE
子句中引用它们:
SELECT
o.ITEM_ID, o.ITEM_PRICE, o.DISCOUNT_AMOUNT, o.QUANTITY,
s.price_total, s.discount_total, s.item_total
FROM ORDER_ITEMS o
CROSS APPLY (SELECT ITEM_PRICE*QUANTITY AS price_total,
DISCOUNT_AMOUNT*QUANTITY AS discount_total,
(ITEM_PRICE-DISCOUNT_AMOUNT)*QUANTITY AS item_total FROM dual) s
WHERE s.item_total > 500
ORDER BY s.item_total;