1

在 SQL 查询中,Oracle 中是否有任何方法可以从其外部的子查询中引用列,或者即使通过不同的方式也能达到这种效果?到目前为止,我在网上阅读的所有内容都没有帮助。

例如(这是我追求的那种东西):

SELECT a.product_code, b.received, b.issued
FROM productinfo a,
 (SELECT SUM(qty_received) AS received, SUM(qty_issued) AS issued
  FROM productdetail b WHERE b.product_code = a.product_code AND active = 1);

我已经尝试了很多不同的变体/组合目前我只是收到类似 ORA-00904: invalid identifier related to the WHERE 子句关系的错误。

目前,如果我作为单独的查询运行,例如:

SELECT product_code FROM productinfo;

然后对于这些记录中的每一个:

SELECT SUM(qty_received) AS received, SUM(qty_issued) AS issued FROM productdetail
WHERE product_code = '(specified)' AND active = 1;

这可能需要半个多小时才能运行 8000 条记录,这简直是愚蠢的。

头发用完了,感谢任何帮助!谢谢你。

4

2 回答 2

6

ORA 错误是因为您无法关联派生表/内联视图 - 您需要使用 JOIN 表示法(ANSI-89 或 92)。

假设您确实需要表中的PRODUCTINFO列,请使用:

SELECT a.product_code, b.received, b.issued
  FROM PRODUCTINFO a
  JOIN (SELECT t.product_code,
               SUM(t.qty_received) AS received, 
               SUM(t.qty_issued) AS issued
          FROM PRODUCTDETAIL t 
         WHERE t.active = 1
      GROUP BY t.produce_code) b ON b.product_code = a.product_code

如果您想查看可能有也可能没有 PRODUCTDETAIL 记录的 productinfo 记录列表,请使用:

   SELECT a.product_code, b.received, b.issued
     FROM PRODUCTINFO a
LEFT JOIN (SELECT t.product_code,
                  SUM(t.qty_received) AS received, 
                  SUM(t.qty_issued) AS issued
             FROM PRODUCTDETAIL t 
            WHERE t.active = 1
         GROUP BY t.produce_code) b ON b.product_code = a.product_code

但是这个例子看起来你可能只需要使用:

 SELECT t.product_code,
        SUM(t.qty_received) AS received, 
        SUM(t.qty_issued) AS issued
   FROM PRODUCTDETAIL t 
   WHERE t.active = 1
GROUP BY t.produce_code
于 2011-02-01T19:28:44.780 回答
0

只需在查询中分组并使用内部联接

SELECT a.product_code, b.received, b.issued
FROM productinfo a
INNER JOIN
 (SELECT product_code, SUM(qty_received) AS received, SUM(qty_issued) AS issued
  FROM productdetail
  WHERE active = 1
  GROUP BY product_code) b on b.product_code = a.product_code
于 2011-02-01T19:18:21.407 回答