简体   繁体   English

带有子查询的 SELECT 语句

[英]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 语句:

  • VendorName (from the Vendors table)供应商名称(来自供应商表)
  • LatestInv (summary function that returns the last entry from InvoiceDate) LatexInv(从 InvoiceDate 返回最后一个条目的汇总函数)
  • AverageInv: (summary function that returns the average from InvoiceTotal) AverageInv:(从 InvoiceTotal 返回平均值的汇总函数)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM