Search code examples
sql-serversql-server-2014-express

SQL Database Select, Sort, and Eliminate Duplicates without DISTINCT


In a sample SQL database, I've got Invoice Totals and Vendor Names on two separate tables.

As a general orientation, here is the current code I've created:

SELECT TOP 5 InvoiceTotal, VendorName
FROM Invoices JOIN Vendors ON Invoices.VendorID = Vendors.VendorID
ORDER BY InvoiceTotal DESC;

I'm looking for the top 5 Invoice Totals displayed WITHOUT repeating any of the Vendor Names. For example, my current output is:

137966.19   Malloy Lithographing Inc
26881.40    Malloy Lithographing Inc
23517.58    Malloy Lithographing Inc
21842.00    Data Reproductions Corp
20551.18    Malloy Lithographing Inc

However, the target output is something like:

137966.19   Malloy Lithographing Inc
21842.00    Data Reproductions Corp
20076.01    Smith & Co
14590.00    Tim's Management LTD
13878.50    HelloWorld Corp

Is this something I can make happen in Management Studio? I've tried implementing DISTINCT, but that doesn't seem to work.

Any help is extremely appreciated.


Solution

  • Would the following work?

    SELECT TOP 5 MAX(InvoiceTotal) AS Total, VendorName
    FROM Invoices JOIN Vendors ON Invoices.VendorID = Vendors.VendorID
    GROUP BY VendorName
    ORDER BY 1 DESC