ReporterTbl
has a one to many relationship with AttachmentTbl
.
In ReporterTbl
, I have an ID (101) and I can have AttachmentTbl
more than one Attachment
s 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 )
Basically, what I am trying to know is given ReporterTbl.ID
, how many Attachment
s do I have?
Table structure:
ReporterTbl Id int {**PrimaryKey**} StartDate datetime PriorityId int PriorityDesc varchar(500 AttachmentTbl: AttachmentId indentity Id {**FK to ReproterTbl**} Filename Content ...
Advertisement
Answer
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
Note: It is important that we are using count(a.id)
, and not count(*)
. This is because count
will ignore null values when we count the results of an expression. If instead we use count(*)
, SQL will count the resulting rows, so any rows from ReporterTbl
that don’t have a matching row in AttachmentTbl
would return a count of 1 because we still return the row due to the left join.