簡體   English   中英

將幾個相似的行與新列合並為一個

[英]Combine several similar rows into one with new columns

原表:

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 行,並帶有新列,如上所示。

我想通過找到相同的“姓名”和“年齡”來做到這一點,並在 count distinct(contact)>0 時使用 DISTINCT CONTACT 之類的情況,但似乎發生了很多語法錯誤。 有沒有更聰明的方法來制作它?

這不是一個簡單的樞軸,因為您需要為樞軸生成一個序列號。 代碼如下:

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()和時髦的分隔符將它們放入一列。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM