[英]SELECT statement with sub-query
Instructions:指示:
Business case: The accounting department would like a reporting of the top ten vendors with their last invoice date and average invoice amount.业务案例:会计部门希望报告前十名供应商的最后发票日期和平均发票金额。
Write a SELECT statement that returns three columns:编写一个返回三列的 SELECT 语句:
Hint: you will need to join two tables before joining to the derived table (the subquery)提示:在加入派生表(子查询)之前,您需要加入两个表
Subquery portion: SELECT statement that returns the top ten VendorID and AverageInv (same name and function as described in the outer query).子查询部分:SELECT 语句,返回前十名 VendorID 和 AverageInv(与外部查询中描述的名称和功能相同)。 Group the results by the appropriate column and sort the results by AverageInv from largest to smallest.按适当的列对结果进行分组,并按AverageInv 从最大到最小对结果进行排序。 Correlate the subquery as BestVendors and join it to the correct table (where both share a key field).将子查询关联为 BestVendors 并将其加入正确的表(两者共享一个关键字段)。
Group the outer query by the appropriate column and sort the results by LatestInv most recent to oldest按适当的列对外部查询进行分组,并按最新到最旧的 LatexInv 对结果进行排序
My code我的代码
SELECT VendorName, MAX(InvoiceDate) AS LatestInv, AVG(InvoiceTotal) AS AverageInv
FROM Vendors v JOIN
(SELECT TOP 10 VendorID, AVG(InvoiceTotal) AS AverageInv
FROM Invoices
GROUP BY VendorID
ORDER BY AverageInv DESC) AS BestVendors
ON v.VendorID = BestVendors.VendorID
GROUP BY VendorName
ORDER BY LatestInv
MAX(InvoiceDate)
has a red line under it as well as AVG(InvoiceTotal)
because they are from the Invoices table. MAX(InvoiceDate)
和AVG(InvoiceTotal)
下面有一条红线,因为它们来自 Invoices 表。 Not the Vendors.不是供应商。 However if I use FROM Invoices
in the outer query then VendorName
won't be recognized?但是,如果我在外部查询中使用FROM Invoices
那么VendorName
将不会被识别? How do I fix this and get the result set that this question is looking for?如何解决此问题并获得此问题正在寻找的结果集?
Also these pics show some sample data from the Invoices and Vendors Table这些图片还显示了发票和供应商表中的一些示例数据
Try this:尝试这个:
SELECT VendorName, BestVendors.LatestInv, BestVendors.AverageInv
FROM Vendors v
INNER JOIN
(
SELECT TOP 10 VendorID
,AVG(InvoiceTotal) AS AverageInv
,MAX(InvoiceDate) AS LatestInv
FROM Invoices
GROUP BY VendorID
ORDER BY AverageInv DESC
) AS BestVendors
ON v.VendorID = BestVendors.VendorID
ORDER BY LatestInv DESC
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.