SQL Server总和返回无效数字

时间:2019-06-15 20:41:33

标签: sql-server

我在查询中使用LEFT JOIN三次来显示用户信息。由于某种原因,倒数第二个LEFT JOIN影响SUM函数的输出。

我尝试删除倒数第二条返回正确值的LEFT JOIN语句。我不明白为什么它会改变值。

SELECT 
    [tbl_users].[id],
    [username],
    COUNT([tbl_password_resets].[id]) as passwordresets,
    SUM(CASE WHEN [tbl_files].[user_id] = [tbl_users].[id] THEN 1 ELSE 0 END) as uploads,
    COUNT([tbl_downloads].[id]) as downloads,
    CAST(SUM(CASE WHEN [tbl_downloads].[liked] = 1 OR [tbl_downloads].[disliked] = 1 THEN 1 ELSE 0 END) AS FLOAT) / NULLIF(COUNT([tbl_downloads].[id]), 0) as ratio,
    [ban]
FROM 
    [tbl_users]
LEFT JOIN 
    [tbl_password_resets] ON [tbl_users].[id] = [tbl_password_resets].[user_id]
LEFT JOIN 
    [tbl_downloads] ON [tbl_users].[id] = [tbl_downloads].[user_id]
LEFT JOIN 
    [tbl_files] ON [tbl_files].[user_id] = [tbl_users].[id]
GROUP BY 
    [tbl_users].[id], [tbl_users].[username], [tbl_users].[ban]

上传结果为9而不是3。

1 个答案:

答案 0 :(得分:1)

如果任何联接表正在重复行,则将影响COUNT和SUM的结果。注释掉聚合,GROUP BY和JOIN以进行测试,并在构建查询时一一添加JOIN,以查看行数会发生什么。属于一组的行越多,将对更多的值进行计数和求和。