【问题标题】:Merge duplicate rows and populate new columns with duplicate data in SQL在 SQL 中合并重复行并使用重复数据填充新列
【发布时间】:2021-03-20 10:25:08
【问题描述】:

这里是 SQL 新手,需要一些指导。任何将不胜感激!

假设我有一个如下的 SQL 表:

id  email            preference
1   john@gmail.com   cake
1   john@gmail.com   fruit
1   john@gmail.com   cheese
1   john@gmail.com   sauce
2   mark@gmail.com   cake
2   mark@gmail.com   sauce
3   kate@gmail.com   tea

我想要做的是合并重复的记录(基于 id 和电子邮件),但也使用“首选项”列中的重复数据来填充新表中的一些附加列。基本上我想达到这个:

id  email           preference1   preference2   preference3   preference4 
1   john@gmail.com  cake          fruit         cheese        sauce
2   mark@gmail.com  cake          sauce         null          null
2   kate@gmail.com  tea           null          null          null

目前有点不知道如何到达这里。

【问题讨论】:

  • 用您正在使用的数据库标记您的问题。
  • 您是否考虑过另一个具有不同结构的表,例如(id、person_id、preference)?这可以让您看到个人的所有偏好并尊重第二范式。

标签: mysql sql merge duplicates


【解决方案1】:

如果你知道你有四个偏好,你可以使用row_number()的条件聚合:

select id, email,
       max(case when seqnum = 1 then preference end) as preference_1,
       max(case when seqnum = 2 then preference end) as preference_2,
       max(case when seqnum = 3 then preference end) as preference_3,
       max(case when seqnum = 4 then preference end) as preference_4
from (select t.*,
             row_number() over (partition by id, email order by preference) as seqnum
      from t
     ) t
group by id, email;

【讨论】:

    猜你喜欢
    • 2019-12-26
    • 1970-01-01
    • 2018-09-17
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 1970-01-01
    • 1970-01-01
    • 2021-11-12
    相关资源
    最近更新 更多