如何从3个表+ count()中选择值

时间:2017-03-31 14:18:36

标签: c# sql sql-server database stored-procedures

我有三张表:

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

如何按每个标题返回发票编号?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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