【问题标题】:Calculating the total number of invoices计算发票总数
【发布时间】:2012-11-15 15:15:38
【问题描述】:
SELECT VendorState, VendorCity
FROM Vendors JOIN COUNT(*)InvoiceDate as TotalInvoices ON Invoices
WHERE VendorState = 'NV' AND 'MI'
我上面的尝试根本不起作用:/我想让它显示
如果状态是 NV 或 MI,则来自 Vendors 表中的 VendorState
供应商城市
每个城市的 TotalInvoices 和最后在 TOTAL 中从 InvoiceDate 中的 Invoices 表中绘制它的计数
【问题讨论】:
标签:
sql
tsql
sql-server-2012
【解决方案1】:
试试
SELECT count(InvoiceDate) as [NumberInvoices], VendorState, VendorCity
FROM Vendors inner JOIN Invoices ON Vendor PK* = Invoices FK
WHERE VendorState in ('NV', 'MI')
按 VendorState、VendorCity 分组
【解决方案2】:
您不能以这种方式加入表格。您需要在两个表之间共享一个共同的值,例如供应商 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')
这与您的其他问题类似
【解决方案3】:
您需要在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 更改为此处应有的任何键。