Return 1 instead of 0 when Count(*) result is Null

与世无争的帅哥 提交于 2019-12-12 11:28:42

问题


My code from SQL Server:

SELECT ESTAGIO.SK_ESTAGIO, ISNULL(count(ESTAGIO.SK_ESTAGIO), 0) as how_many
 from ESTAGIO
 left join ESTAGIARIO
 on ESTAGIARIO.SK_ESTAGIO = ESTAGIO.SK_ESTAGIO
 group by
    ESTAGIO.SK_ESTAGIO

When "ESTAGIO.SK_ESTAGIO" doesn't exist in the table "ESTAGIARIO" it returns 1 instead of 0, I already tried to use ISNULL(), NULLIF() and COALESCE() and still couldn't find the problem that is making the query above returning 1 when it should be 0.


回答1:


You are counting the wrong field. Do it like this, taking the field from the outer joined table ESTAGIARIO (not from ESTAGIO):

SELECT ESTAGIO.SK_ESTAGIO, Count(ESTAGIARIO.SK_ESTAGIO) as how_many
 from ESTAGIO
 left join ESTAGIARIO
 on ESTAGIARIO.SK_ESTAGIO = ESTAGIO.SK_ESTAGIO
 group by
    ESTAGIO.SK_ESTAGIO

BTW, count can never return null.



来源:https://stackoverflow.com/questions/44155025/return-1-instead-of-0-when-count-result-is-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!