计算发票总数

时间:2012-11-15 15:15:39

标签: sql tsql sql-server-2012

SELECT VendorState, VendorCity
FROM Vendors JOIN COUNT(*)InvoiceDate as TotalInvoices ON Invoices
WHERE VendorState = 'NV' AND 'MI'

我上面的尝试根本不起作用:/我想让它显示

如果状态为NV或MI,则来自Vendors表的VendorState

VendorCity

每个城市的

和TotalInvoices以及TOTAL的末尾从发票表中的InvoiceDate中计算它的数量

3 个答案:

答案 0 :(得分:0)

尝试

SELECT count(InvoiceDate)as [NumberInvoices],VendorState,VendorCity FROM供应商内部JOIN发票开启供应商PK * = 发票FK 在哪里VendorState('NV','MI') 按VendorState,VendorCity分组

答案 1 :(得分:0)

你不能以这种方式加入表格。您需要在两个表之间共享一个公共值,例如供应商ID或其他东西。

首先,它是:

select a.vendorstate, a.vendorcity, sum(invoices) as 'the sum'
from vendors a inner join invoices b on a.vendorid = b.vendorid
group by a.vendorstate, a.vendorcity
where state in ('NV','MI')

这与你的其他问题类似

答案 2 :(得分:0)

您需要在Invoices表格中指定外键才能将Vendors加入Invoices。这是一个例子:

SELECT v.VendorState, v.VendorCity, COUNT(i.InvoiceDate) AS Invoices
FROM Vendors v WITH(NOLOCK)
JOIN Invoices i WITH(NOLOCK) ON i.VendorID = v.VendorID
WHERE v.VendorState IN ('NV', 'MI')
GROUP BY v.VendorState, v.VendorCity
ORDER BY v.VendorState, v.VendorCity

显然,您需要将联接i.VendorID = v.VendorID更改为此处的任何键。