如果重复,则将多个列值合并到新列中
Combine multiple column values into new column(s) if it's a duplicate
我什至确定这是否可以完成,但我充满希望。当前使用 mysql 5.7
我想显示所有列,如果它们是基于 phone 值的重复条目。然后我想select所有数据从更高的id号到多个新列。
我不知道如何创建一个可以正确显示所有重复项的视图,否则这会更容易理解。我使用以下查询来获取数据。
原版table
id customer_name customer_email customer_phone comments
1 Jack jack@jack.com 111-111-1111
2 Jill jill@jill.com 111-111-1111
3 Tim tim@tim.com 222-222-2222
4 Tonya tonya@tonya.com 222-222-2222
预期结果
id customer_name customer_email customer_phone spouse_name spouse_email comments
1 Jack jack@jack.com 111-111-1111 Jill jill@jill.com Jill jill@jill.com
3 Tim tim@tim.com 222-222-2222 Tonya tonya@tonya.com Tonya tonya@tonya.com
理想情况下,所有 3 列都将被填充,但 spouse_name 和 spouse_email 更重要,因为我总是可以将它们组合起来并插入评论中。
如果你是 运行 MysQL 8.0,你可以用 window 函数和条件聚合来做到这一点:
select
max(case when rn = 1 then customer_name end) as customer_name_1,
max(case when rn = 1 then customer_email end) as customer_email_1,
customer_phone,
max(case when rn = 2 then customer_name end) as customer_name_2,
max(case when rn = 2 then customer_email end) as customer_email_2
from (
select t.*,
row_number() over(partition by customer_phone order by id) rn
from mytable t
) t
group by customer_phone
当两行具有相同的 customer_phone
时,这会将具有最小 id
的行的名称和电子邮件放在前两列,然后是另一行。
备注:
如果超过两行,第二行之后的行将被忽略
如果只有一行,最后两列为空
您的数据中没有任何内容可以区分客户和“配偶”,因此我改为使用数字前缀作为列名
我什至确定这是否可以完成,但我充满希望。当前使用 mysql 5.7
我想显示所有列,如果它们是基于 phone 值的重复条目。然后我想select所有数据从更高的id号到多个新列。
我不知道如何创建一个可以正确显示所有重复项的视图,否则这会更容易理解。我使用以下查询来获取数据。
原版table
id customer_name customer_email customer_phone comments
1 Jack jack@jack.com 111-111-1111
2 Jill jill@jill.com 111-111-1111
3 Tim tim@tim.com 222-222-2222
4 Tonya tonya@tonya.com 222-222-2222
预期结果
id customer_name customer_email customer_phone spouse_name spouse_email comments
1 Jack jack@jack.com 111-111-1111 Jill jill@jill.com Jill jill@jill.com
3 Tim tim@tim.com 222-222-2222 Tonya tonya@tonya.com Tonya tonya@tonya.com
理想情况下,所有 3 列都将被填充,但 spouse_name 和 spouse_email 更重要,因为我总是可以将它们组合起来并插入评论中。
如果你是 运行 MysQL 8.0,你可以用 window 函数和条件聚合来做到这一点:
select
max(case when rn = 1 then customer_name end) as customer_name_1,
max(case when rn = 1 then customer_email end) as customer_email_1,
customer_phone,
max(case when rn = 2 then customer_name end) as customer_name_2,
max(case when rn = 2 then customer_email end) as customer_email_2
from (
select t.*,
row_number() over(partition by customer_phone order by id) rn
from mytable t
) t
group by customer_phone
当两行具有相同的 customer_phone
时,这会将具有最小 id
的行的名称和电子邮件放在前两列,然后是另一行。
备注:
如果超过两行,第二行之后的行将被忽略
如果只有一行,最后两列为空
您的数据中没有任何内容可以区分客户和“配偶”,因此我改为使用数字前缀作为列名