没有返回行时,TSQL COUNT显示0

时间:2012-11-12 16:54:12

标签: sql sql-server tsql join count

我有一个表文档,列出了所有文档及其相关信息。我想要做的是,对于一组精选的作者,要计算他们在过去一年中创作的所有文档。对于每个文档,我们都有一个列来存储作者姓名和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'。但对于我的生活,我无法弄清楚如何去做。我很确定它需要像this

3 个答案:

答案 0 :(得分:3)

从Authors表开始,对文档表执行左外连接。这意味着您需要将条件移动到外部联接...

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

答案 1 :(得分:2)

据推测,如果他们没有撰写任何文件,他们就不会在文件表中记录。 我猜你有一个作者表或类似的?

这样的东西
SELECT 
a.[AuthorID] As "Author ID",
RTRIM(a.[AuthorFirstName]) + ' ' + RTRIM(a.[AuthorLastName]) AS "Author", 
COUNT(Document.ID) AS "Number of Docs Authored"
FROM Author a
LEFT OUTER JOIN
Document
ON A.AuthorId = Document.AuthorId
AND  [CompletedStatus] = 'Yes' 
AND     [CompletedOn] >= DATEADD(d, -365, getdate())
WHERE     A.[AuthorID] IN (<list of author ID's>) 
GROUP BY a.[AuthorID], a.[AuthorFirstName], a.[AuthorLastName]

答案 2 :(得分:2)

如果你有作者表,你可以这样做:

SELECT  a.AuthorID As "Author ID",
        RTRIM([a.AuthorFirstName]) + ' ' + RTRIM([a.AuthorLastName]) AS "Author", 
        COUNT(Document.ID) AS "Number of Docs Authored"
FROM Authors a left outer join
     Document d
     on a.[AuthorID] = d.[AuthorID] and
        d.CompletedStatus = 'Yes' and
       [CompletedOn] >= DATEADD(d, -365, getdate())
WHERE a.[AuthorID] IN (<list of author ID's>) and
GROUP BY a.AuthorID, a.AuthorFirstName], a.authorLastName
ORDER BY [Number of Docs Signed] DESC

请注意文档中的所有条件都在on子句中。否则,对于没有文档的作者,值将为NULL。

如果您没有authors表,可以动态创建一个:

with authors as (
    select <id> as id, <firstname> as authorFirstName, <lastname> as authorLastName union all
    select . . .
)

然后使用上面的查询。您需要使用名称信息填写每位作者。