'How to count one to many relationships
ReporterTbl has a one to many relationship with AttachmentTbl.
In ReporterTbl, I have an 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
)
Basically, what I am trying to know is given ReporterTbl.ID, how many Attachments 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
...
Solution 1:[1]
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
Solution 2:[2]
given ReporterTbl.ID how many attachments i have.
Wouldn't it just be:
select count(*) from AttachmentTbl where id = @ID;
Solution 3:[3]
I had to group by the first element in the SELECT clause as well as the item I am aggregating on:
SELECT p.Name, COUNT(c.PersonId) AS Count
FROM People AS p
LEFT JOIN Contacts AS c
ON (p.Id = c.PersonId)
GROUP BY c.PersonId, p.Name;
I am not really sure why I had to do this, it isn't the case when using SQLite, which is what I am used to.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Quassnoi |
| Solution 2 | James Curran |
| Solution 3 | Michael Murphy |
