1

我有一个 sql 一直给我一个异常,我不知道为什么,我的问题是 avg(x.Points) 出于某种原因返回 null,在这种情况下如何让它返回 0?

    UPDATE a
SET a.Points = (SELECT avg(x.Points) FROM 
   (SELECT TOP 5 * 
    FROM [dbo].[AlbumImages] i 
    WHERE i.AlbumId = a.Id 
    AND i.Points > 0 
    ORDER BY i.Points Desc) x)
FROM  [dbo].[Albums] a
    join [dbo].[Users] u on a.UserId = u.Id
WHERE u.DoRanking = 1

这给了我例外

Cannot insert the value NULL into column 'Points', 
table 'Cosplay.dbo.Albums'; column does not allow nulls. UPDATE fails.
4

1 回答 1

3

您可以检查AVG 功能上的ISNULL 。当表达式为空时,ISNULL 需要返回第二个参数。

UPDATE a
SET a.Points = (SELECT ISNULL(avg(x.Points),0) 
                FROM (SELECT TOP 5 * 
                      FROM [dbo].[AlbumImages] i 
                      WHERE i.AlbumId = a.Id 
                      AND i.Points > 0 
                      ORDER BY i.Points Desc) x)
FROM  [dbo].[Albums] a
    join [dbo].[Users] u on a.UserId = u.Id
WHERE u.DoRanking = 1
于 2013-06-13T18:18:48.650 回答