如何将查询转换为相关查询

时间:2017-03-27 21:07:10

标签: sql-server tsql correlated-subquery

与相关查询斗争,并想知道某人是否可以分享更好的示例/说明如何创建相关查询。'我确实理解内部/外部查询是相互依赖的,但仍然不相信我的解决方案是准确的或者在编码时感觉非常确定并且想到实践转换我已经努力相关的查询。以下是工作查询的示例:

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;

感谢您的指导和建议。

2 个答案:

答案 0 :(得分:1)

我认为这就是你想要的:

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;

相关子查询在这里不合适。您将从多个表返回结果。只需使用JOIN正确执行GROUP By

答案 1 :(得分:1)

由于您要从products和orderdetails表中进行选择,因此您应仅使用基于联接的解决方案:

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子句(也已修复)。