简体   繁体   中英

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:

  • VendorName (from the Vendors table)
  • LatestInv (summary function that returns the last entry from InvoiceDate)
  • AverageInv: (summary function that returns the average from 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). Group the results by the appropriate column and sort the results by AverageInv from largest to smallest. Correlate the subquery as BestVendors and join it to the correct table (where both share a key field).

Group the outer query by the appropriate column and sort the results by LatestInv most recent to oldest

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. Not the Vendors. However if I use FROM Invoices in the outer query then VendorName won't be recognized? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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