2017-03-31 59 views
0

我有三個表:如何從3個表中選擇值+計數()

tbl_Publisher [Publisher_ID, addr,account-num,...,city]; 
tbl_Title [Title_ID, frequency, publisher,.., Publisher_ID]; 
tbl_Invoice [Invoice_ID, ordered_Date,...,Title_ID]; 

我想通過出版迴歸的標題列表,並且每個題目都有它包含發票的計數。在一個結果集中。 我使用一個存儲過程如下:

PROCEDURE [dbo].[usp_GetTitlesbyPublisher] 
    -- Add the parameters for the stored procedure here 
    @PublisherID INT 


AS 
BEGIN 
    -- SET NOCOUNT ON added to prevent extra result sets from 
    -- interfering with SELECT statements. 


    -- Insert statements for procedure here 
    SELECT Title_ID,TitleName,pub_type,Frequency , Holdings ,tbl_Title.publisher ,section ,tbl_Title.Publisher_ID from tbl_Title, tbl_Publisher 
    where tbl_Title.Publisher_ID = tbl_Publisher.Publisher_ID 
    and @PublisherID = tbl_Publisher.Publisher_ID 

END 

我怎樣才能通過每個標題返回發票的號碼?

+0

標記您正在使用的dbms。該代碼是特定於產品的。 – jarlh

+0

使用SQL Server的存儲過程,我添加了需要的標籤。 –

+0

但我看不到sql-server標籤。 – jarlh

回答

1

你或許可以用GROUP BY做到這一點:

SELECT t.Title_ID, t.TitleName, p.pub_type, 
     t.Frequency, Holdings, t.publisher, section, 
     t.Publisher_ID, count(i.Invoice_ID) as NoOfInvoices 
from tbl_Title t 
inner join tbl_Publisher p on t.Publisher_ID = p.Publisher_ID 
left join tbl_Invoice i on i.Title_ID = t.Title_ID 
where @PublisherID = p.Publisher_ID 
group by t.Title_ID, t.TitleName, p.pub_type, t.Frequency, 
     Holdings, t.publisher, section, t.Publisher_ID 
+0

我沒有想要承擔連接:) – logixologist

+0

@logixologist在我看來,如果他們不是'INNER JOIN's – Stephen

+0

,我同意這是沒有意義的。 OP具有內連接,但採用舊連接方式。 –

0

不檢查語法這一點。

SELECT COUNT(tbl_Invoice.Invoice_ID) 'InvoiceCount',Title_ID,TitleName,pub_type,Frequency, Holdings ,tbl_Title.publisher ,section ,tbl_Title.Publisher_ID 
FROM tbl_Title 
INNER JOIN tbl_Publisher ON tbl_Publisher.Publisher_ID = tbl_Title.Publisher_ID 
INNER JOIN tbl_Invoice ON tbl_Invoice.Invoice_ID = tbl_Title.Invoice_ID 
WHERE tbl_Publisher.Publisher_ID = @PublisherID 
GROUP BY 
    Title_ID,TitleName,pub_type,Frequency, Holdings ,tbl_Title.publisher ,section ,tbl_Title.Publisher_ID 
+0

這隻會返回一個標題和發票數量。我想返回發佈商擁有的所有標題。 –