Skip to content
Advertisement

Combining some of the rows and sum them up in oracle sql

I`m working on some data manipulation and have table:

Source Table

Customer  Account   AMT   Charge_1  Charge_2 Charge_3
AB           E      C      a            g      m
AB           E      C      b            h      n
AB           E      C      c            i      o
AB           B      W      d            j      p
AB           B      W      e            k      q
AB           R      V      f            l      r

I need to have and output to look like:

Customer  Account   AMT   Charge_1  Charge_2  Charge_3
AB           E       C     a+b+c     g+h+i     m+n+o
AB           B       W       d+e       j+k       p+q
AB           R       V         f         l         r

enter image description here

Please suggest what can I use to combine and sum up those. I appreciate any input!

Thank you

Advertisement

Answer

You can use aggregation. Values are strings, so you probably want to concatenate them rather than sum them (which makes no sense in string context):

select
    customer,
    account
    listagg(charge_1, '+') charge_1,
    listagg(charge_2, '+') charge_2,
    listagg(charge_3, '+') charge_3
from mytable
group by customer, account

You can control the ordering of the results in the concatenated strings with the within group clause:

select
    customer,
    account
    listagg(charge_1, '+') within group(order by charge_1) charge_1,
    listagg(charge_2, '+') within group(order by charge_2) charge_2,
    listagg(charge_3, '+') within group(order by charge_3) charge_3
from mytable
group by customer, account
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement