2010-09-09 20 views
6

ReporterTbl ha uno a molti rapporti con AttachmentTbl.Come contare uno a molti rapporti

In ReporterTbl, ho un ID (101) e posso avere AttachmentTbl più di un Attachment s connessi con 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 
) 

In sostanza, quello che sto cercando di conoscere è dato ReporterTbl.ID, quanti Attachment s ho?

Struttura della tabella:

ReporterTbl 

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

    AttachmentTbl: 

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

risposta

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

proposta ReporterTbl.ID quante allegati ho.

Non sarebbe solo essere:

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

Certo, se vuoi un giornalista alla volta. –

+1

Ma era quello che chiedeva .... –

5

Se si desidera ottenere tutti i campi da Reported (non solo ID), questo vi farà risparmiare un JOIN:

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