当Count(*)结果为Null时,返回1而不是0

问题描述:

我从SQL Server获得的代码

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

当 ESTAGIARIO表中不存在 ESTAGIO.SK_ESTAGIO时,它返回1而不是0,我已经尝试使用ISNULL(), NULLIF()和COALESCE()仍然找不到上面的查询在应为0时返回1的问题。

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.

您正在计算错误的字段。这样做,从外部联接表 ESTAGIARIO 中获取字段(不是从 ESTAGIO 中获取):

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

顺便说一句, count 永远不会返回

BTW, count can never return null.