我有一个查询,它有三层。也就是说,我有一个主查询,它有一个标量子查询,它还包含一个标量子查询。
底层标量查询返回两个不同的值,其中中级子查询返回平均值。但是,它不是接收当前值的底层查询,而是平均表中的所有值。
有谁知道如何将当前顶级查询结果的值正确传递给底部子查询?
代码示例:
Select Product,
Description,
(Select Avg(Mfg_Cost, Purchasing_Cost)
FROM (Select Mfg_Cost,
Purchasing Cost
From Cost
Where Cost.Product = Products.Product))
From Products;
答案 0 :(得分:0)
你不能只使用JOIN和GROUP BY,如下所示:
Select p.Product,
p.Description,
Avg(c.Mfg_Cost),
Avg(c.Purchasing_Cost)
From Products p
INNER JOIN
Cost c
ON c.Product = p.Product
GROUP BY p.Product, p.Description;
通常,如果需要从子查询返回多个值:
Select p.Product,
p.Description,
q2.AvgMfg_Cost,
q2.AvgPurchasing_Cost
From Products p INNER JOIN
(
Select c.Product,
Avg(c.Mfg_Cost) AS AvgMfg_Cost,
Avg(c.Purchasing_Cost) AS AvgPurchasing_Cost
From Cost c
Group by c.Product
) AS q2
on q2.Product = p.Product;
在Microsoft SQL Server中,您还可以使用Common Table Expression (CTE)