Mysql 将两个相似的行合并为一个具有新列的行
原始表格:Mysql 将两个相似的行合并为一个具有新列的行,mysql,sql,Mysql,Sql,原始表格: Name Age Contact_type Contact Alex 20 SMS 12345 Alex 20 Email abc@gmail.com Alex 20 SMS 54321 Bob 35 SMS 23456 我想把它做成: Name
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
如果名称和年龄重复,请将2(或更多)行与新列合并为1行,如上所示
我想通过查找相同的“Name”和“Age”来实现这一点,并在count DISTINCT(CONTACT)>0时使用不同的CONTACT,比如
case,但似乎出现了很多语法错误。有更聪明的方法吗?使用条件聚合
来做到这一点
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
谢谢在这种情况下效果很好。但是,如果表格变得更复杂,因为编辑的问题?那么这是一个新的问题