SQL Average使用INNER JOIN忽略NULL值

时间:2015-12-02 17:33:48

标签: sql sql-server-2012

我正在尝试平均多个列,但我正在接收NULL值。我想用值0替换NULL。我还需要INNER JOIN几个表来获取我需要的所有信息。

这是我到目前为止所做的:

select 
    m.mstr_list_item_desc,
    p.last_name,
    p.first_name,
    AVG((l.percentage_1 + l.percentage_2 + l.percentage_3 + l.percentage_4 +          l.percentage_5 + l.percentage_6 +l.percentage_7 + l.percentage_8 + l.percentage_9 + l.percentage_10 + l.percentage_11 + l.percentage_12 + l.percentage_13)/13) as Total_average
from LMA_ob_compliance_ as l
INNER JOIN patient_encounter as pe
    on l.enc_id=pe.enc_id
INNER JOIN provider_mstr as p
    on p.provider_id=pe.rendering_provider_id
INNER JOIN mstr_lists as m
    on m.mstr_list_item_id=p.provider_subgrouping1_id
group by m.mstr_list_item_desc, p.last_name, p.first_name
order by p.last_name asc

这些百分比列中的大部分都是NULL,但我希望能够在我的计算中将NULL包括为0。

非常感谢任何帮助!

2 个答案:

答案 0 :(得分:3)

使用ISNULLNULL替换为您想要的值

ISNULL(l.percentage_1, 0) + isnull(l.percentage_2, 0) + ...

答案 1 :(得分:0)

由于您无法实现Jakub的答案(我赞成,因为它是正确的),这是您对ISNULL的应用程序全部查询所有13次。为了便于阅读,我还冒昧地修改了一些格式,并将一些硬编码值更改为.0结束,以确保你永远不会被隐式转换所取代。

select 
    m.mstr_list_item_desc,
    p.last_name,
    p.first_name,
    AVG(
        (
        ISNULL(l.percentage_1, 0.0) + 
        ISNULL(l.percentage_2, 0.0) + 
        ISNULL(l.percentage_3, 0.0) + 
        ISNULL(l.percentage_4, 0.0) + 
        ISNULL(l.percentage_5, 0.0) + 
        ISNULL(l.percentage_6, 0.0) +
        ISNULL(l.percentage_7, 0.0) + 
        ISNULL(l.percentage_8, 0.0) + 
        ISNULL(l.percentage_9, 0.0) + 
        ISNULL(l.percentage_10, 0.0) + 
        ISNULL(l.percentage_11, 0.0) + 
        ISNULL(l.percentage_12, 0.0) + 
        ISNULL(l.percentage_13, 0.0)
        )
        /13.0) as Total_average
from 
    LMA_ob_compliance_ as l
    INNER JOIN patient_encounter as pe on l.enc_id=pe.enc_id
    INNER JOIN provider_mstr as p on p.provider_id=pe.rendering_provider_id
    INNER JOIN mstr_lists as m on m.mstr_list_item_id=p.provider_subgrouping1_id
group by 
    m.mstr_list_item_desc, 
    p.last_name, 
    p.first_name
order by 
    p.last_name asc