将几个相似的行合并为一个新列

时间:2015-07-18 17:54:31

标签: sql mysqli

原始表:

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'来做到这一点,并且在计数distinct(contact)> 0时使用DISTINCT CONTACT就像情况一样,但似乎发生了很多语法错误。有没有更智能的方法来制作它?

1 个答案:

答案 0 :(得分:0)

这不是一个微不足道的枢轴,因为您需要为旋转生成序列号。代码如下:

select name,
       max(case when seqnum = 1 then contact_type end) as contacttype1,
       max(case when seqnum = 1 then contact end) as contact1,
       max(case when seqnum = 2 then contact_type end) as contacttype2,
       max(case when seqnum = 2 then contact end) as contact2,
       max(case when seqnum = 3 then contact_type end) as contacttype3,
       max(case when seqnum = 3 then contact end) as contact3
from (select ot.*,
             (@rn := if(@n = name, @rn + 1,
                        if(@n := name, 1, 1)
                       )
             ) as seqnum
      from originaltable ot cross join
           (select @rn := 0, @n := '') params
      order by name
     ) ot
group by name;

注意:这假设您知道最大联系人数。如果您不这样做,则需要使用动态SQL或使用group_concat()和时髦分隔符将它们放入一列。