I have one table, Documents, that lists all documents and various information about them. What I’m trying to do is, for a select group of authors, get a count of all documents they’ve authored in the past year. For each document, we have a column to store the Author name and ID.
I am currently getting what I want with the query below, but my problem is I also need to list all authors that haven’t authored any documents. (So, for the Number of Docs Signed column they’d have a zero value) Here’s what I have now:
SELECT
[AuthorID] As "Author ID",
RTRIM([AuthorFirstName]) + ' ' + RTRIM([AuthorLastName]) AS "Author",
COUNT(Document.ID) AS "Number of Docs Authored"
FROM Document
WHERE [CompletedStatus] = 'Yes'
AND [AuthorID] IN (<list of author ID's>)
AND [CompletedOn] >= DATEADD(d, -365, getdate())
GROUP BY [AuthorID], [AuthorFirstName], [AuthorLastName]
ORDER BY [Number of Docs Signed] DESC
From reading around on SO I know I think I need some kind of subquery that I can join in order to show a ‘0’ when there are no rows returned by COUNT. But for the life of me I can’t figure out how to do it. I’m pretty sure it needs to be something like this.
Start from the Authors table and do a left outer join to the documents table. This means you need to move the criteria into the outer join…