Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL – Return a Sum of Counts

My data represents a 1 to many relationship between applicants and documents attached to each applicant.

I have a query that will return how many documents are attached to each application:

Select a.ApplicationId, count(att.AttachmentId) as _Count from [db].Application a
inner join [db].Attachment att
on att.ApplicationId=a.ApplicationId
group by a.applicationid, att.ApplicationId

That returns data like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

ApplicationId    _Count
_____________    ______
1                   3
2                   1
3                   9
4                   6
5                   3

What I would like is a summary how many cases have 1 document, how many have 2 documents, how many have 9 documents, etc.. Like this:

DocCount             Total
_______              _____
1                      42
2                      33
3                      29
4                      51

>Solution :

You can get this value by applying an outer query to your current query. Just use the _Count value as the group expression in the outer query.

select  _Count As DocCount, count(*) As Total
from
(
    Select a.ApplicationId, count(att.AttachmentId) as _Count from [db].Application a
    inner join [db].Attachment att
    on att.ApplicationId=a.ApplicationId
    group by a.applicationid, att.ApplicationId
)as X
group by
    _Count
order by
   _Count
    
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading