我试图围绕子查询(相关)。虽然这本书解释了(MS SQL Server 2012),但我仍然有点困惑。使用三个表,订单,产品和订单详细信息我想找到运往美国的所有产品的总和。我提出了以下查询,但不太明白我是如何到达那里的,除了相关性引用了'其中'在外部查询中。有人可以纠正我的工作并提供比书更好的解释吗?
SELECT p.productid, p.productname, SUM(qty * od.unitprice) AS TotalAmount
FROM Production.Products AS p
JOIN Sales.OrderDetails AS od
ON p.productid = od.productid
WHERE N'USA' IN
(SELECT o.shipcountry
FROM Sales.Orders AS o
JOIN Sales.OrderDetails AS od
ON o.orderid = od.orderid
WHERE shipcountry = N'USA')
GROUP BY p.productid, p.productname;
答案 0 :(得分:1)
SELECT
p.ProductID
, p.ProductName
, SUM(qty * od.UnitPrice) as [Total_Amount]
FROM
Production.Products productid
JOIN Sales.OrderDetails as od on p.productid = od.product
JOIN SalesOrders as o on o.OrderID = od.OrderID
WHERE
o.Shipcountry in ('USA')
Group BY
p.ProductID,
P.ProductName
以下应该可行 - 您在技术上不需要子查询。只会使查询陷入困境。