简体   繁体   中英

SQL create new column based on the one-to-one or one-to-many relationship between two original columns

I have a table with the fields id , name , and type . An id can be linked to one or two names or no names. If an id is linked to two names, the type for each of the names can be red or blue but they cannot be both blue or both red like below.

id  name  type   
1   null  null
2   ai3   red
3   wz2   blue
4   5ef   blue
4   l2e   red 

If an id does have two names attached to it I want to create a new category called both . I'm not sure how to use a CASE statement to accomplish this.

id  name  type cat   
1   null  null null
2   ai3   red  red
3   wz2   blue blue
4   5ef   blue both
4   l2e   red  both

Use window functions:

select t.*,
       (case when min(type) over (partition by id) <> max(type) over (partition by id)
             then 'both'
             else min(type) over (partition by id)
        end) as cat
from t;

I believe something like this may work, may need to be tweaked but that's the way most CASE statements work:

 ALTER TABLE t2
 ADD `cat` as (CASE WHEN t2.type = 'Blue' Then 'Blue'
                 WHEN t2.type = 'Blue' AND t2.type = 'Red' Then 'both'
                 WHEN t2.type = 'Red' Then 'Red'
            END)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM