2

我有一张表Documents,其中列出了所有文档和有关它们的各种信息。我要做的是,对于一组选定的作者,计算他们在过去一年中创作的所有文档。对于每个文档,我们都有一个列来存储作者姓名和 ID。

我目前通过下面的查询得到了我想要的,但我的问题是我还需要列出所有没有创作任何文档的作者。(因此,对于Number of Docs Signed列,它们的值为零)这是我现在所拥有的:

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

通过阅读 SO,我知道我认为我需要某种可以加入的子查询,以便在 COUNT 没有返回行时显示“0”。但是对于我的生活,我不知道该怎么做。我很确定它需要是这样的。

4

3 回答 3

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
于 2012-11-12T16:57:01.053 回答
2

大概如果他们没有创作任何文档,他们就不会在文档表中记录。我猜你有一个 Authors 表或类似的表?

就像是

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]
于 2012-11-12T17:00:30.560 回答
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。

如果您没有作者表,则可以即时创建一个:

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

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

于 2012-11-12T17:00:33.223 回答