我正在使用chinook数据库和sqlite3。我的目标是返回一张发票清单,其中包含发票ID,发票日期和特定客户发票上的项目数。前两个非常简单,
SELECT InvoiceId, InvoiceDate
FROM invoices
WHERE CustomerId = 2;
返回:
1 |2009-01-01 00:00:00
12 |2009-02-11 00:00:00
67 |2009-10-12 00:00:00
196|2011-05-19 00:00:00
219|2011-08-21 00:00:00
241|2011-11-23 00:00:00
293|2012-07-13 00:00:00
但是,发票行项目位于另一个表格中。我可以通过以下方式计算与特定发票相对应的那些:
SELECT count(*)
FROM invoice_items
WHERE Invoiceid = 12;
返回14
但我想返回一个列表:
1 |2009-01-01 00:00:00|2
12|2009-02-11 00:00:00|14
答案 0 :(得分:0)
您的查询需要内部联接;它看起来像这样:
create table test(f1 varchar(256) null)
go
create proc sp_test(@p varchar(256) = 'Hello ')
as
insert test
select @p
return 1
go
declare @p varchar(256) = 'World'
EXEC('EXEC sp_test @p = ''Hello ''; select * from test')
EXEC('EXEC sp_test @p = ' + @p + '; select * from test')
drop proc sp_test
go
drop table test
go
当然,我猜测了SELECT
invoices.InvoiceId, invoices.InvoiceDate,
COUNT(DISTINCT(items.ID)) AS Items
FROM
invoices
JOIN
invoice_items AS items ON invoices.ID = itemsID
GROUP BY invoices.InvoiceId
列的名称
答案 1 :(得分:0)
尝试如下的子查询:
select invoiceid, invoicedate,
(select count(*) from invoice_items where invoiceid = i.invoiceid) as CountInvoiceItems
from invoices
获取所有结果,否则您可以将您的where子句重新添加到发票12中。
答案 2 :(得分:0)
要获取特定客户的发票,您应该使用加入
这是一个例子:
5