子查询FROM子句SQL Server

时间:2015-03-26 07:08:15

标签: sql sql-server subquery

我在FROM子句中编写子查询时遇到问题。

编写一个返回三列的SELECT语句:

  • VendorName(来自Vendors表)
  • LatestInv(从InvoiceDate返回最后一个条目的汇总函数)
  • AverageInv(从InvoiceTotal返回平均值的汇总函数)

提示:在加入派生表(子查询)之前,您需要连接两个表

子查询部分SELECT语句,返回前十VendorIDAverageInv(与外部查询中描述的名称和功能相同)。按适当的列对结果进行分组,并按AverageInv从最大到最小对结果进行排序。将子查询关联为BestVendors并将其连接到正确的表(两者共享一个关键字段)。

按适当的列对外部查询进行分组,并按最近的LatestInv将结果排序为最旧的。“

代码:

SELECT 
    VendorName, 
    MAX(InvoiceDate) AS LatestInv, 
    AVG(InvoiceTotal) AS AverageInv
FROM 
    Vendors 
JOIN 
    Invoices ON Vendors.VendorID = Invoices.VendorID
(SELECT TOP 10 
     VendorID,
     AVG(InvoiceTotal) AS AverageInv
 FROM Invoices
 GROUP BY VendorID
 ORDER BY AverageInv DESC) AS BestVendor ON Vendors.VendorID = BestVendor.VendorID
GROUP BY 
    VendorName
ORDER BY 
    LatestInv DESC;

这是我到目前为止所做的但是不正确,任何帮助将不胜感激

1 个答案:

答案 0 :(得分:0)

在子查询之前添加JOIN:

SELECT 
    VendorName, 
    MAX(InvoiceDate) AS LatestInv, 
    AVG(InvoiceTotal) AS AverageInv
FROM 
    Vendors 
JOIN 
    Invoices ON Vendors.VendorID = Invoices.VendorID 
JOIN 
(SELECT TOP 10 
     VendorID,
     AVG(InvoiceTotal) AS AverageInv
 FROM Invoices
 GROUP BY VendorID
 ORDER BY AverageInv DESC) AS BestVendor
    ON Vendors.VendorID = BestVendor.VendorID
GROUP BY 
    VendorName
ORDER BY 
    LatestInv DESC;