SQL 命令未正确结束,涉及 table 别名

SQL command not properly ended, concerning with table aliases

我知道 oracle 不允许对 table 别名使用 AS 命令,因此有人建议我使用如下解决方案。

SELECT Temp.avgsale
FROM (SELECT o.received, AVG(p.price*d.qty+d.sfee) avgsale
     FROM orders o, parts p, odetails d
     GROUP BY o.received) Temp
WHERE Temp.avgsale=(SELECT MIN(Temp.avgsale) FROM Temp);

但是,当我 运行 它时出现以下错误:ERROR at line 4: ORA-00942: table or view does not exist。当我尝试在 SELECT 查询的开头设置别名时,我也会遇到类似的错误:Temp (SELECT ...)。任何帮助将不胜感激,因为我无法确定查询有什么问题。

问题是当解析 where 子句中的子查询时,table 别名 temp 可能尚未定义。您可以改用常见的 table 表达式:

WITH Temp AS (
    SELECT o.received, AVG(p.price*d.qty+d.sfee) avgsale
    FROM orders o, parts p, odetails d
    GROUP BY o.received
    )

SELECT Temp.avgsale
FROM Temp
WHERE Temp.avgsale = (SELECT MIN(Temp.avgsale) FROM Temp);

看起来查询还有另一个问题;它缺少需要的订单、零件和细节 table 之间的连接。你可能想要这样的东西:

WITH Temp AS (
    SELECT o.received, AVG(p.price*d.qty+d.sfee) avgsale
    FROM orders o
    JOIN odetails od ON o.orderid = od.orderid
    JOIN parts p ON p.partid = od.partid 
    GROUP BY o.received
    )

SELECT Temp.avgsale
FROM Temp
WHERE Temp.avgsale = (SELECT MIN(Temp.avgsale) FROM Temp);

请注意,我只是在猜测您的列名是什么,因为您没有在问题中包含任何相关信息。

此外,也许您想要订单匹配 min(temp.avgsale) 而不仅仅是 min()?如果是这样,请将最后一部分更改为:

SELECT Temp.received, Temp.avgsale
FROM Temp
WHERE Temp.avgsale = (SELECT MIN(Temp.avgsale) FROM Temp);

这个查询对我来说更有意义。

您似乎想要获取数据,其中给定日期(received?那是一个日期吗?)的平均订单销售额是最小平均销售额?您可以使用 window(分析)函数来执行此操作。请注意 - 我在下面猜测您的连接条件,因为您的原始查询使用的是笛卡尔连接。

SELECT received, avgsale FROM (
    SELECT received, avgsale, RANK() OVER ( ORDER BY avgsale ) AS rn
      FROM (
        SELECT o.received, AVG(p.price * d.qty + d.sfee) AS avgsale
          FROM orders o INNER JOIN odetails d
            ON o.order_id = d.order_id
         INNER JOIN parts p
            ON d.part_id = p.part_id
         GROUP BY o.received
    )
) WHERE rn = 1;

请注意,这将检索 received 的所有值,以及相应的平均销售额,其中平均销售额等于最小值。如果您只想要一行,请使用 ROW_NUMBER() 代替 RANK()

如果您更喜欢用 CTE 编写此代码,则可以按如下方式进行:

WITH temp AS (
    SELECT o.received, AVG(p.price * d.qty + d.sfee) AS avgsale
      FROM orders o INNER JOIN odetails d
        ON o.order_id = d.order_id
     INNER JOIN parts p
        ON d.part_id = p.part_id
     GROUP BY o.received
)
SELECT received, avgsale FROM (
    SELECT received, avgsale, RANK() OVER ( ORDER BY avgsale ) AS rn
      FROM temp
) WHERE rn = 1;