按计数加总

时间:2014-10-28 14:05:36

标签: sql tsql count sum case

我正在尝试根据特定列的计数编号创建求和。如果您查看下面选择中的最后一行,您会看到我尝试实现CASE语句。但是,它会生成所有NULL个值。我相信我理解为什么(每行都有一组独特的值),但我不知道如何解决我的问题。

SELECT 
    TotalFilesProduced.ReviewDate,
    TotalFilesProduced.FileReviewedByUserID,
    TotalFilesProduced.FileSource,
    TotalFilesProduced.FilesIndexed TotalIndexed,
    TotalFilesProduced.FileNumberofPages TotalFileNumberofPages,
    TotalFilesProduced.FilesProduced,
    CASE WHEN COUNT(DISTINCT FileReviewedByUserID) > 1 THEN SUM(TotalFilesProduced.FilesIndexed) END
FROM 
(SELECT 
    CAST(ibfp.FileReviewedDate AS DATE) ReviewDate,
    ibfp.FileReviewedByUserID,
    FileSource,
    COUNT(*) FilesProduced,
    COUNT(DISTINCT ibf.InboundFileID) FilesIndexed,
    SUM(CASE WHEN ibfp.FromPage = ibfp.ToPage THEN 1
    ELSE ibfp.ToPage-ibfp.FromPage + 1 END) [FileNumberofPages]
FROM 
    dbo.InboundFilePartitions ibfp
    INNER JOIN dbo.InboundFiles ibf ON ibfp.InboundFileID = ibf.InboundFileID
WHERE
        CAST(ibfp.FileReviewedDate AS DATE) >= '10/22/2014'
    and CAST(ibfp.FileReviewedDate AS DATE) <= '10/22/2014'
    and ibf.ProjectID in (110)
GROUP BY
    CAST(ibfp.FileReviewedDate AS DATE),
    ibfp.FileReviewedByUserID,
    FileSource 
) TotalFilesProduced
GROUP BY 
    TotalFilesProduced.ReviewDate,
    TotalFilesProduced.FileReviewedByUserID,
    TotalFilesProduced.FileSource,
    TotalFilesProduced.FilesIndexed,
    TotalFilesProduced.FileNumberofPages,
    TotalFilesProduced.FilesProduced

以下是进一步说明的示例 - 此处生成NULL的UserID 1036很好,因为它只出现一次,但对于804 - 我想将TotalIndexed列加起来{{1区域应为139(对于出现804的两个实例)

NULL

1 个答案:

答案 0 :(得分:1)

如评论中所述 这将永远是假的

CASE WHEN COUNT(DISTINCT FileReviewedByUserID) > 1 

因为

GROUP BY ibfp.FileReviewedByUserID 

你还有其他一些奇怪的东西

        CAST(ibfp.FileReviewedDate AS DATE) >= '10/22/2014'
    and CAST(ibfp.FileReviewedDate AS DATE) <= '10/22/2014'

相同
CAST(ibfp.FileReviewedDate AS DATE) = '10/22/2014'

更奇怪的东西

SUM(CASE WHEN ibfp.FromPage = ibfp.ToPage THEN 1
    ELSE ibfp.ToPage-ibfp.FromPage + 1 END) [FileNumberofPages]

相同
SUM(ibfp.ToPage-ibfp.FromPage + 1) [FileNumberofPages] 

不确定你要做的是什么,但是分组上的小组并不常见