'PIVOT function returning NULL values and ISNULL not removing

I have a query using PIVOT function that has NULL values that wish to replace with 0 in the cell. I have tried to add the ISNULL into the sub query against O7CRAM but that did not remove the NULL values

    select
        * 
    from 
    (
      select 
      O7ORNO,
      O7CRID,
      O7CRAM
    
      from MVXJDTA.OOLICH 
    ) src
    pivot
    (
      sum(O7CRAM)
      for O7CRID in ([PNP], [DTY], [HAN])
    ) piv
     order by O7ORNO;

The issue I have now is the ISNULL and where to place it to remove the NULL values.

Current Output:

O7ORNO PNP DTY HAN
100000329 0.85 NULL NULL

Desired Output:

O7ORNO PNP DTY HAN
100000329 0.85 0.00 0.00


Solution 1:[1]

Using the PIVOT syntax, the ISNULL or COALESCE needs to be done in the outer query.

select O7ORNO, 
 isnull(PNP, 0) as PNP,
 isnull(DTY, 0) as DTY, 
 isnull(HAN, 0) as HAN
from (
  select O7ORNO, O7CRID, O7CRAM
  from MVXJDTA.OOLICH 
) src
pivot (
  sum(O7CRAM) 
  for O7CRID in (PNP, DTY, HAN)
) pvt
order by O7ORNO;
O7ORNO PNP DTY HAN
100000329 0.85 0.00 0.00

db<>fiddle here

Conditional aggregation is another method for pivotting.

select O7ORNO
, SUM(CASE O7CRID WHEN 'PNP' THEN O7CRAM ELSE 0 END) AS PNP
, SUM(CASE O7CRID WHEN 'DTY' THEN O7CRAM ELSE 0 END) AS DTY
, SUM(CASE O7CRID WHEN 'HAN' THEN O7CRAM ELSE 0 END) AS HAN
from MVXJDTA.OOLICH  
group by O7ORNO
order by O7ORNO;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1