带空值的 SQL 计数

TSQL Counting with Nulls

我有一个 table 从 ED 入院和出院算什么。这就是 table 的样子

我正在尝试获取入院和出院的总数。像

录取 - 100 放电 - 200

有没有办法用 NULL 值做到这一点?

select 
    sum(case when Admitted is null then 0 else Admitted end) Admitted,    
    sum(case when DischargedFromED is null then 0 else DischargedFromED end) as DischargedFromED
from MyMagicalTable;

select
    sum(coalesce(Admitted, 0)) Admitted,
    sum(coalesce(DischargedFromED, 0)) DischargedFromED
from MyMagicalTable;

只需使用sum();

select sum(admitted) as admitted, sum(DischargedFromED) as DischargedFromED
from t;

聚合函数忽略 NULL 个值。

如果您担心 NULL 值出现在 之后 sum(),然后使用 coalesce() 之后:

select coalesce(sum(admitted), 0) as admitted,
       coalesce(sum(DischargedFromED), 0) as DischargedFromED
from t;

以上假定列是数字。如果是其他类型,需要转为数字。