原始表格:
Name Age Contact_type Contact
Alex 20 SMS 12345
Alex 20 Email abc@gmail.com
Alex 20 SMS 54321
Bob 35 SMS 23456
我想把它变成:
Name Age Contact_type1 Contact_1 Contact_type2 Contact_2 Contact_type3 Contact_3
Alex 20 SMS 12345 Email abc@gmail.com SMS 23456
Bob 35 SMS 23456
如果 name 和 age 重复,将 2(或更多)行合并为 1 行,并使用新列,如上所示。
我想通过找到相同的“姓名”和“年龄”,并使用 DISTINCT CONTACT 来做到这一点,例如 case when count distinct(contact)>0
但似乎出现了很多语法错误。有没有更聪明的方法来制作它?
最佳答案
使用条件聚合
来做到这一点
select Name,Age,
max(case when Contact = 'SMS' then Contact end) as Contact_1,
max(case when Contact = 'Email' then Contact end) as Contact_2
from yourtable
group by Name, Age
关于mysql - 将两个相似的行合并为一个新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31487637/