我有一个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.
答案 0 :(得分: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