I have been having difficulties with a piece of script I am creating, and was hoping for some insight into what I am doing wrong
QUESTION:
use a correlated subquery to return invoice(s) for each vendor, representing the vendor’s oldest invoice (the one with the earliest date). Each row should include these four columns: vendor name, invoice number, invoice date, and invoice total.
MY SCRIPT:
SELECT DISTINCT Vendor_Name,
Invoice_number AS OLDEST_INVOICE,
Invoice_date,
invoice_total
FROM Vendors v
JOIN Invoices i ON v.vendor_id = i.vendor_id
WHERE invoice_date IN (
SELECT DISTINCT MIN(invoice_date)
FROM invoices i
JOIN vendors v ON i.vendor_id = v.vendor_id
GROUP BY v.vendor_name
)
ORDER BY Invoice_Date;
Currently, my code is giving too many results back, essentially I am having trouble establishing that invoice_numbers are only to be returned for the lowest date possible.
You need to restrict the join to those invoices for the specific vendor, AND that has the earliest date…
You don;t menmtion whether the Invoice table has a surrogate PK… If it doesn’t, try:
If the invoice table has a surrogate PK, say InvoiceId, then try this:
The former only uses one subquery, but the latter is truer (more clearly expresses) the intent of the query’s intent.