I have a table that looks like this:
AMT TYPE
100 red, yellow, green, purple
200 red, green, blue, yellow
90 pink, blue, light red
......
What I want is to add up the amounts by color. For example, a final output should be:
AMT TYPE
300 red
300 yellow
300 green
290 blue
190 other
Notice that 1. I don't want to include light red
in red
and 2. I want to include all colors other than red, yellow, green, blue in to a new category "other".
My current code is
select sum(red), ... from (
select
case when trim(regexp_substr(type, red',1,1,'i')) is not null
then amt
else 0 end as red
......
from mytable)
But it doesn't solve the problems I mentioned earlier. I also tried the following method, but it becomes so slow that it never ends. (Or maybe there is some error in this code?)
select color, sum(amt)
from (
select trim(regexp_substr(type,'[^,]+', 1, level)) as color
from mytable
connect by level <= regexp_count(type, ',')+1)
group by color
How can I solve this?
Thank you!