在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这样的错误:与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条记录,这些记录只是简单的愚蠢。
头发耗尽,任何帮助都赞赏!!谢谢。
答案 0 :(得分: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
如果您想查看productinfo记录的列表,可能有也可能没有PRODUCTDETAIL记录,请使用:
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
答案 1 :(得分: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