sql查询应返回0而不是NULL
问题描述:
SELECT SUM(Pairs) AS previous_pairs FROM payout
WHERE user_id = '100001'
如果表中存在记录,则上面的查询工作正常.如果没有ID为"100001"的单行,则返回NULL.
我想要的是如果没有ID为``100001''的行存在,那么它应该返回0而不是NULL.
任何帮助将不胜感激.
above query works fine if there are record present in the table. If there are not single row with id ''100001'', then it returns NULL.
What i want is if there are no row present with id ''100001'' then it should return 0 instead of NULL.
Any help would be appreciated.
答
SELECT ISNULL(SUM(Pairs), 0) AS previous_pairs FROM payout
WHERE user_id = '100001'
ISNULL函数为: http://technet.microsoft .com/en-us/library/ms184325.aspx [ ^ ]
它检查表达式是否返回null,然后将其替换为您提供的替换值.
ISNULL function as: http://technet.microsoft.com/en-us/library/ms184325.aspx[^]
It checks whether expression returns null, then replaces it with what you provide as replacement value.
另一种方法是使用 ^ ]函数.
Another way is to use COALESCE()[^] function.