Skip to content
Advertisement

How to SUM multiple DECODE values?

I have the following decodes in my SELECT case:

DECODE (table_name, 'RECHNUNG', SUM(beleg_betrag_offen) ) as re_be_of,
DECODE (table_name, 'GUTSCHRIFT', SUM(beleg_betrag_offen) ) as gs_be_of,
DECODE (table_name, 'ZAHLUNG', SUM(beleg_betrag_offen) ) as za_be_of

I want to add up those 3 values (every DECODE has always some results) but I can’t. When I write a simple

re_be_of + gs_be_of + za_be_of

I don’t even see any result. Does anyone know where my mistake is?

Advertisement

Answer

Actually, should have probably been vice versa: SUM(DECODE), not DECODE(SUM), e.g.

with temp as
  (select sum(decode(table_name, 'RECHNUNG'  , beleg_betrag_offen)) as re_be_of,
          sum(decode(table_name, 'GUTSCHRIFT', beleg_betrag_offen)) as gs_be_of,
          sum(decode(table_name, 'ZAHLUNG'   , beleg_betrag_offen)) as za_be_of
   from your_table
  )
select re_be_of,
       gs_be_of,
       za_be_of,
       --
       re_be_of + gs_be_of + za_be_of total
from temp       

NVL function might need to be used.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement