2010-09-09 3 views
6

ReporterTbl a une relation à plusieurs avec AttachmentTbl.Comment compter une à plusieurs relations

En ReporterTbl, j'ai un ID (101) et je peux avoir AttachmentTbl plus d'un Attachment s en rapport avec ReporterTbl.Id

SELECT  
ISNULL(ReporterTbl.Id, 0) AS Id, 
CONVERT(char(10), ReporterTbl.StartDate, 101) AS StartDate, 
ISNULL(ReporterTbl.PriorityId, 0) AS PriorityId, 
ISNULL(dbo.ReporterTbl.PriorityDesc, '') AS PriorityDesc, 
(select  
    ReporterTbl.Id, 
    COUNT(dbo.AttachmentTbl.Id) AS attachment_Id 
FROM   
dbo.AttachmentTbl RIGHT OUTER JOIN 
ReporterTbl ON dbo.AttachmentTbl.Id = ReporterTbl.Id 
GROUP BY ReporterTbl.Id) AS IsAttachment 
) 

Fondamentalement, ce que je suis en train de savoir est donné ReporterTbl.ID, combien de Attachment s est-ce-que j'ai?

Structure de la table:

ReporterTbl 

    Id int {**PrimaryKey**} 
    StartDate datetime 
    PriorityId int 
    PriorityDesc varchar(500 

    AttachmentTbl: 

    AttachmentId indentity 
    Id {**FK to ReproterTbl**} 
    Filename 
    Content 
    ... 

Répondre

18
select r.id, count(a.id) as Count 
from ReporterTbl r 
left outer join AttachmentTbl a on r.id = a.id 
group by r.id 
2

donné ReporterTbl.ID combien de pièces jointes que j'ai.

Ne serait-il juste:

select count(*) from AttachmentTbl where id = @ID; 
+0

Bien sûr, si vous voulez un journaliste à la fois. –

+1

Mais c'est ce qu'il a demandé .... –

5

Si vous souhaitez obtenir tous les champs de signalés (non seulement ID), cela vous permettra d'économiser JOIN:

SELECT r.*, 
     (
     SELECT COUNT(*) 
     FROM AttachmentTbl a 
     WHERE a.id = r.id 
     ) AS AttachmentCount 
FROM ReportedTbl r 
Questions connexes