如何用子查询和CTE替换联接?

时间:2019-10-07 13:24:14

标签: sql-server subquery inner-join

您好,我正在为我解决的每个问题练习多种选择。 我想将带有join的查询转换为带有子查询的查询,并使用cte转换为另一个查询。

但是我发现很难做到:

SELECT 
    C.CompanyName, MAX(OD.UnitPrice*OD.Quantity)MaxOdPrice, 
    MIN(OD.UNITPRICE*OD.Quantity) MinOdPrice
FROM [Order Details] OD 
JOIN Orders O       ON OD.OrderID=O.OrderID
JOIN Customers C    ON O.CustomerID=C.CustomerID
GROUP BY C.CompanyName

谢谢

2 个答案:

答案 0 :(得分:0)

您仍然需要JOINS,但这是一个简单的CTE,我希望可以对进一步进行操作提供一些想法

;With cteCustomers
AS(
    SELECT  X.CustomerID, X.CompanyName
    FROM    Customers X
)
SELECT 
    C.CompanyName, MAX(OD.UnitPrice*OD.Quantity)MaxOdPrice, 
    MIN(OD.UNITPRICE*OD.Quantity) MinOdPrice
FROM [Order Details]    OD 
JOIN Orders             O   ON  OD.OrderID=O.OrderID
JOIN cteCustomers       C   ON  O.CustomerID=C.CustomerID
GROUP BY C.CompanyName

答案 1 :(得分:0)

完全未经测试,但我认为类似这样的方法无需加入即可。

select C.CompanyName,
   max(select MAX(UnitPrice * Quantity)
       from [Order Details]
       where OrderID in (select distinct OrderID
                         from Orders
                         where CustomerID in (select CustomerID
                                              from Customers innerC
                                              where innerC.CompanyName = C.CompanyName
                                             )
                       )
       group by OrderID
      ) AS MaxOdPrice
FROM Customers C
GROUP BY C.CompanyName

我只显示MaxOdPrice。