我有一个表 Documents ,其中列出了所有文档以及有关它们的各种信息。对于一组选定的作者,我想要做的是获得他们在过去一年中创作的所有文档的数量。对于每个文档,我们都有一列来存储作者姓名和ID。
我目前正在通过下面的查询获得所需的信息,但是我的问题是我还需要列出所有未编写任何文档的作者。(因此,对于“ 已签名的文档数” 列,它们的值为零)这是我现在所拥有的:
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
通过反复阅读,我知道我认为我需要某种子查询才能加入,以便在COUNT不返回任何行时显示“0”。但是对于我的一生,我不知道该怎么做。
从Authors表开始,然后左向外部联接到documents表。这意味着您需要将条件移动到外部联接中。
SELECT [AuthorID] As "Author ID", RTRIM([AuthorFirstName]) + ' ' + RTRIM([AuthorLastName]) AS "Author", COUNT(Document.ID) AS "Number of Docs Authored" FROM Author a LEFT OUTER JOIN Document d on d.AuthorID = a.ID AND [CompletedStatus] = 'Yes' AND [CompletedOn] >= DATEADD(d, -365, getdate()) WHERE a.ID IN (<list of author ID's>) GROUP BY a.[ID], [AuthorFirstName], [AuthorLastName] ORDER BY [Number of Docs Signed] DESC