简体   繁体   中英

SQL Server 2012 Joining columns from two tables into one

I have two tables in different places

the end result has to be

VendorName  InvoiceNumber  InvoiceTotal

VendorName is in a table called Vendors

InvoiceNumber and InvoiceTotal are in a table called Invoices

it needs to show all the vendors in the result even if the vendors dont have any invoices, display the largest invoice totals first DESC and sort the Vendor Names in Alphabetical order.

I tried to Join the Invoices into my

SELECT VendorName FROM Vendors 

but I cannot figure out the syntax :/

Use a LEFT JOIN to include those vendors with no invoices like so:

SELECT 
  v.VendorName, i.InvoiceNumber, i.InvoiceTotal
FROM Vendors v
LEFT JOIN Invoices i ON v.Id = i.VendorID
ORDER BY i.InvoiceTotal DESC, v.VendorName ASC

You will want to use a LEFT JOIN to join the two tables on the column that relates the two tables. Using the LEFT JOIN will return all of the vendors even if they do not have an entry in the invoices table:

select v.vendorname,
    i.invoicenumber,
    i.invoicetotal
from vendors v
left join invoices i
    on v.vendorid = i.vendorid  -- this is the column relating the two tables
order by i.invoicetotal DESC, v.vendorname ASC

If you need help learning JOIN syntax, here is a great visual explanation of joins

You need an OUTER JOIN . Assuming the PK/FK is VendorID :

SELECT v.VendorName, i.InvoiceNumber, i.InvoiceTotal
FROM Vendors v
LEFT OUTER JOIN Invoices i ON v.VendorID = i.VendorID
ORDER BY v.VendorName   ASC
      ,  i.InvoiceTotal DESC

Try:

SELECT Vendors.VendorName, Invoices.InvoiceNumber, Invoices.InvoiceTotal 
FROM Vendors LEFT JOIN Vendors.VendorID on Invoices.VendorId 
ORDER BY Invoices.InvoiceTotal DESC

Do you want your ventors to be grouped all together, or can a vendor be in the resultset more then 1 time? You can play with SUM(Invoices.InvoiceTotal) for example to get the total of InvoiceTotals.

Do you mean something like :

select VendorName
      ,Count(InvoiceAmount) As InvoiceNumber
      ,Sum(InvoiceAmount) As InvoiceTotal
  from Vendor
  left join Invoices on Vendor.VendorId = Invoices.VendorId
 group by VendorName
 order by 3 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