SQL Server 2012将两个表中的列连接成一个

时间:2012-11-08 14:32:25

标签: sql tsql sql-server-2012

我在不同的地方有两张桌子

最终结果必须是

VendorName  InvoiceNumber  InvoiceTotal

VendorName位于名为Vendors

的表格中

InvoiceNumberInvoiceTotal位于名为Invoices

的表格中

即使供应商没有任何发票,也需要显示结果中的所有供应商,首先显示最大发票总额DESC并按字母顺序对供应商名称进行排序。

我尝试将发票加入我的

SELECT VendorName FROM Vendors 

但我无法弄清楚语法:/

5 个答案:

答案 0 :(得分:1)

使用LEFT JOIN包含那些没有发票的供应商:

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

答案 1 :(得分:1)

您将需要使用LEFT JOIN来连接与这两个表相关的列上的两个表。使用LEFT JOIN将返回所有vendors,即使它们在invoices表中没有条目:

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

如果您需要帮助学习JOIN语法,这里有一个很棒的visual explanation of joins

答案 2 :(得分:1)

您需要OUTER JOIN。假设PK / FK为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

答案 3 :(得分:1)

尝试:

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

您是否希望将您的发布者组合在一起,或者供应商是否可以在结果集中使用多次?例如,您可以使用SUM(Invoices.InvoiceTotal)来获取InvoiceTotals的总数。

答案 4 :(得分:0)

你的意思是:

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