与相关查询作斗争,想知道是否有人可以分享一个更好的示例/解释如何创建"相关查询"。我确实了解内部/外部查询相互依赖,但仍然不相信我的解决方案是准确的,或者在编码它们时感觉非常确定,并想到练习转换我正在努力关联的查询。下面是工作查询的示例:
SELECT p.productid, p.productname, SUM(od.unitprice - od.discount) * od.qty
AS total_amount
FROM Production.Products AS p
JOIN Sales.OrderDetails AS od
ON p.productid = od.productid
JOIN Sales.Orders AS o
ON od.orderid = o.orderid
WHERE o.shipcountry = 'USA';
--EDITED--Converted to Correlated Query
因此,如果我想将其转换为相关的子查询,这应该是解决方案。感谢您的指导和建议。
SELECT productid, productname
FROM Production.Products AS t1
WHERE productid = (SELECT SUM(od.unitprice - od.discount) * od.qty AS
total_amount
FROM Sales.OrderDetails AS od
JOIN Sales.Orders AS o
ON od.orderid = o.orderid
JOIN Production.Products AS t2
ON t2.productid = t1.productid
WHERE o.shipcountry = 'USA')
GROUP BY productid, productname;
感谢您的指导和建议。
由于您同时从产品和订单明细表中进行选择,因此应仅使用基于联接的解决方案:
select p.productid,
p.productname,
SUM((od.unitprice - od.discount) * od.qty) as total_amount
from Production.Products as p
join Sales.OrderDetails as od on p.productid = od.productid
join Sales.Orders as o on od.orderid = o.orderid
where o.shipcountry = 'USA'
group by p.productid,
p.productname
请注意添加的group by
子句,因为您正在使用sum
(也是固定的(。
我认为这就是你想要的:
SELECT p.productid, p.productname,
SUM(od.unitprice - od.discount) * p.qty AS total_amount
FROM Production.Products p JOIN
Sales.Orders o JOIN
Sales.OrderDetails od
ON o.orderid = od.orderid
WHERE o.shipcountry = 'USA'
GROUP BY p.productid, p.productname;
此处不适合使用相关的子查询。 您正在从多个表返回结果。 只需使用GROUP By
正确执行JOIN
即可。