Skip to content
Advertisement

Joining two rows into one rows (different column) in oracle

I have table with values like this

ID   |Name     |Balance     |Type   |ProductName
1     Abdol     10000        1       RAID100
2     HIVE      5000000      2       RAID100
3     Ade       20000        1       RAID200
4     Koi       30000        1       RAID100

I want to re-arrange the table using select script to:

ProductName | Balance_Type_1 | Balance_Type_2
RAID100       40000            5000000
RAID200       20000            0                 

I’ve tried nested case when, but it always create one column with Product-name followed by 0 value besides and repeated.

Thank You

Advertisement

Answer

You want aggregation :

select productname, 
       sum(case when type = 1 then balance else 0 end) as balance_type1,
       sum(case when type = 2 then balance else 0 end) as balance_type2
from table t
group by productname;

Run the aggregation query whenever is needed, do not create summary table structure in the database. It will be difficult to manage.

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