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
...
In SQL, you can make a database query and use the COUNT function to get the number of rows for a particular group in the table. Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; COUNT(column_name) will not include NULL values as part of the count.
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
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
given ReporterTbl.ID how many attachments i have.
Wouldn't it just be:
select count(*) from AttachmentTbl where id = @ID;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With