合并两个连接的结果

时间:2017-06-18 15:04:48

标签: sql sql-server tsql

我有3个表:Book,Invoice,Download最后两个有Book的外键的地方。我需要知道每本书的成功发票和下载数量。为了得到结果,我有2个查询。第一个显示每本书的编号发票:

select b.Title, sum(i.price)
from Book b, Invoice i
where i.BookId = b.Id and i.State = 'successful'
group by b.Title

最后一个显示每本书的下载次数:

select b.Title, count(1)
from Book b, Download d 
where d.BookId = b.Id and d.State = 'successful'
group by b.FarsiTitle

我希望将结果看作一个表,因此我有3列:

  

book_title,invoice_count,download_count

怎么可能?

2 个答案:

答案 0 :(得分:3)

我认为最简单的方法是相关子查询:

blog.com/project

如果您想使用project.com,则需要在 select b.*, (select count(*) from invoice i where i.BookId = b.Id and i.State = 'successful' ) as num_invoices, (select count(*) from download d where d.BookId = b.Id and d.State = 'successful' ) as numdownloads from book b; 之前汇总以获得正确的计数。

编辑:

在SQL Server中,您可以使用JOIN

JOIN

这与相关子查询非常相似,但允许您进行多次计算。

答案 1 :(得分:0)

简单的联合一切都很好,如下所示:

select b.Title, sum(i.price)
from Book b join Invoice i
on i.BookId = b.Id and i.State = 'successful'
group by b.Title

UNION ALL

select b.Title, count(1)
from Book b join Download d 
on d.BookId = b.Id and d.State = 'successful'
group by b.FarsiTitle