-1

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

最终结果必须是

VendorName  InvoiceNumber  InvoiceTotal

VendorName在一个名为的表中Vendors

InvoiceNumber并且InvoiceTotal在一个名为的表中Invoices

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

我试图将发票加入我的

SELECT VendorName FROM Vendors 

但我无法弄清楚语法:/

4

5 回答 5

1

尝试:

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

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

于 2012-11-08T14:40:30.577 回答
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
于 2012-11-08T14:37:19.610 回答
1

您将希望使用 aLEFT 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语法方面需要帮助,这里有一个很好的连接可视化解释

于 2012-11-08T14:36:37.987 回答
1

使用 aLEFT 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
于 2012-11-08T14:34:36.637 回答
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
于 2012-11-08T14:35:43.343 回答