简体   繁体   中英

Select rows where ID is same but Name contains different data in more than one record

ID  Name  
---------
1    ABC         
1    123              
2    BCD         
3    CDE         
4    AAA         
4    ZZZ         

Desired Result

ID  Name1      Name2 
---------------------
1    ABC        123                    
2    BCD        NULL
3    CDE        NULL 
4    AAA        ZZZ    

You can use aggregation:

select id, min(name) as name1,
       nullif(max(name), min(name)) as name2
from t
group by id;

If you just want a list of all names, then use a single column for the names and use group_concat() :

select id, group_concat(name) as names
from t
group by id;

You could just use aggregation:

select id, min(name) name1, case when min(name) <> max(name) then max(name) name2
from mytable
group by id

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