Hi,
Could someone revise my sql code so that it can run faster? Thank you very much.
I have a table with id and cat. There may be multiple rows for the same ID with different cat. cat only has two values 'a' or 'b'.
I want to create a new_cat column that has values of 'a only', 'a+b' and 'b only'. The following is my code
with a_only as (
select distinct id, 'a only' as new_cat
from database
where cat = 'a' and id not in (
select distinct id
from database
where cat = 'b'
)
),
a_n_b as (
select distinct id, 'a+b' as new_cat
from database
where cat = 'a' and id in (
select distinct id
from database
where cat = 'b'
)
),
b_only as (
select distinct id, 'b only' as new_cat
from database
where cat = 'b' and id not in (
select distinct id
from database
where cat = 'a'
)
)
------ union three sql -----
select * from a_only
union
select * from a_n_b
union
select * from b_only