views:

33

answers:

3

ReporterTbl is one to many relationship >>> AttachmentTbl

in ReporterTbl i have Id (101) and i can have AttachmentTbl more than one attachments related with 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
)

bascially, what i am trying to know is.

given ReporterTbl.ID how many attachments i have.

structure:

 ReporterTbl

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

    AttachmentTbl:

    AttachmentId indentity
    Id {**FK to ReproterTbl**}
    Filename
    Content
    ...
+2  A: 
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
RedFilter
`ISNULL` is redundant here: `COUNT` can never return `NULL`.
Quassnoi
Thanks Quassnoi, fixed.
RedFilter
A: 

given ReporterTbl.ID how many attachments i have.

Wouldn't it just be:

select count(*) from AttachmentTbl where id = @ID;
James Curran
Sure, if you want one reporter at a time.
OMG Ponies
Now this is getting ridiculous.
Denis Valeev
But that was what he asked for....
James Curran
A: 

If you want to get all fields from Reported (not only ID), this will save you a JOIN:

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