带有Pivot的SQL查询即使使用Isnull也显示空值

时间:2017-10-12 09:12:41

标签: sql sql-server tsql

我使用此查询但是它一直显示我的NULL值而不是0,我已经尝试了很多东西并且无法让它在空值上返回0。

select p.* from 
    (
    select  'Ordenado Base' as Custos, nome, sum(isnull(prre.ere,0)) as OBase 
    from pr
    inner join prre on pr.prstamp = prre.prstamp
    where year(pr.data) = 2017 and prre.cr = 1
    group by nome
    ) as Tabela1
    Pivot(
     sum(Tabela1.Obase)
    for nome in ([Alexandra Maria da Costa Migueis],[ALEXANDRE PEDRO GOMES FREITAS],[Amílcar Leonardo dos Santos],[Ana Filipa Leitão Costa Martins Claro Viana Machado],[ANA PATRICIA FRED FILIPE]) as P

1 个答案:

答案 0 :(得分:1)

you need to change your query to include ISNULL in the select list. Assume that you do not have any Obase value for say [Alexandra Maria da Costa Migueis] then the value under it will be NULL

select 
        Custos,
        [Alexandra Maria da Costa Migueis]=ISNULL([Alexandra Maria da Costa Migueis],0),
        [ALEXANDRE PEDRO GOMES FREITAS]=ISNULL([ALEXANDRE PEDRO GOMES FREITAS],0),
        [Amílcar Leonardo dos Santos]=ISNULL([Amílcar Leonardo dos Santos],0),
        [Ana Filipa Leitão Costa Martins Claro Viana Machado]=ISNULL([Ana Filipa Leitão Costa Martins Claro Viana Machado],0),
        [ANA PATRICIA FRED FILIPE]=ISNULL([ANA PATRICIA FRED FILIPE],0)
from 
    (
        select  
            'Ordenado Base' as Custos, 
            nome, 
            sum(isnull(prre.ere,0)) as OBase 
        from pr
        inner join prre on pr.prstamp = prre.prstamp
            where year(pr.data) = 2017 and prre.cr = 1
        group by nome
    ) as Tabela1
    Pivot
    (
    sum(Tabela1.Obase)
    for nome in 
        (
        [Alexandra Maria da Costa Migueis],
        [ALEXANDRE PEDRO GOMES FREITAS],
        [Amílcar Leonardo dos Santos],
        [Ana Filipa Leitão Costa Martins Claro Viana Machado],
        [ANA PATRICIA FRED FILIPE]
        )-- was missing
    ) as P