ORACLE关于标识符的问题

时间:2011-07-07 19:51:35

标签: sql oracle

如果您创建了一个函数和名称,那么您的语句中是否可以使用该名称?

例如,在下面的代码中,我将sellprice-buyprice命名为PROFIT但我似乎无法再次使用它,因为它作为无效标识符出错。如果我不能这样做,请告诉我如何在该栏中显示最大利润条目。

SELECT item, buyprice, sellprice,
sellprice-buyprice as “PROFIT”
FROM auctions
WHERE PROFIT = (select MAX(PROFIT) from auctions); 

3 个答案:

答案 0 :(得分:2)

你能试试这句话吗: select * from (select item, buyprice, sellprice, sellprice-buyprice as “PROFIT” from auctions order by 4 desc) where rownum = 1;

答案 1 :(得分:0)

您可以在where子句中使用函数名称,引用别名在那里无效。

SELECT item, buyprice, sellprice,
sellprice-buyprice as “PROFIT”
FROM auctions
WHERE sellprice-buyprice = (select MAX(PROFIT) from auctions);

如果您真的想使用别名

,则可以执行以下操作
select item, buyprice, sellprice, profit
from
(
  SELECT item, buyprice, sellprice, sellprice-buyprice as “PROFIT”
  FROM auctions)
)
WHERE PROFIT = (select MAX(PROFIT) from auctions);

答案 2 :(得分:0)

除了使用子查询之外,正如已经建议的那样,您可以通过子查询重构来实现这一点:

WITH auctions_p AS (SELECT   item,
                             buyprice,
                             sellprice,
                             sellprice - buyprice AS profit
                      FROM   auctions)
SELECT   item,
         buyprice,
         sellprice,
         profit
  FROM   auctions_p
 WHERE   profit = (SELECT   MAX(profit) FROM auctions_p);

如果你要使用这个并且使用11g,你可以通过将它定义为虚拟列来永久保持这个计算:

ALTER TABLE auctions ADD (profit AS (sellprice - buyprice));

SELECT   item,
         buyprice,
         sellprice,
         profit
  FROM   auctions
 WHERE   profit = (SELECT   MAX(profit) FROM auctions);