SQL连接没有重复行的字符串

时间:2016-05-26 00:59:57

标签: sql postgresql

我在桌子上有这样一句话:

id  email1             email2                email3             all
1   jean@hotmail.fr    jean@hotmail.fr       jean2@hotmail.fr   NULL
2   herve@hotmail.fr   NULL                  herve@hotmail.fr   NULL
3   pierre@hotmail.fr  NULL                  pierre@gmail.com   NULL
4   roger@hotmail.fr   roger@free.fr         NULL               NULL
5   norbert@hotmail.fr NULL                  norbert@hotmail.fr NULL
6   jules@hotmail.fr   contact@free.fr       julius@gmail.com   NULL

有了这样的要求:

UPDATE mytable SET all=concat_ws(';', email1, email2, email3);

我得到了:

id  email1             email2                email3             all
1   jean@hotmail.fr    jean@hotmail.fr       jean2@hotmail.fr   jean@hotmail.fr;jean@hotmail.fr;jean2@hotmail.fr
2   herve@hotmail.fr   NULL                  herve@hotmail.fr   herve@hotmail.fr;herve@hotmail.fr
3   pierre@hotmail.fr  NULL                  pierre@gmail.com   pierre@hotmail.fr;pierre@gmail.com
4   roger@hotmail.fr   roger@free.fr         NULL               roger@hotmail.fr;roger@free.fr
5   norbert@hotmail.fr NULL                  norbert@hotmail.fr norbert@hotmail.fr;norbert@hotmail.fr
6   jules@hotmail.fr   contact@free.fr       julius@gmail.com   jules@hotmail.fr;contact@free.fr;julius@gmail.com

但是我还需要删除重复的电子邮件给optain:

id  email1             email2                email3             all
1   jean@hotmail.fr    jean@hotmail.fr       jean2@hotmail.fr   jean@hotmail.fr;jean2@hotmail.fr
2   herve@hotmail.fr   NULL                  herve@hotmail.fr   herve@hotmail.fr
3   pierre@hotmail.fr  NULL                  pierre@gmail.com   pierre@hotmail.fr;pierre@gmail.com
4   roger@hotmail.fr   roger@free.fr         NULL               roger@hotmail.fr;roger@free.fr
5   norbert@hotmail.fr NULL                  norbert@hotmail.fr norbert@hotmail.fr
6   jules@hotmail.fr   contact@free.fr       julius@gmail.com   jules@hotmail.fr;contact@free.fr;julius@gmail.com

感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

这可能不是理想的解决方案,但您可以尝试使用case ... end子句来确定重复项:

UPDATE mytable SET all=concat_ws(
     ';'
     , email1
     , case when email2 in (email1) then null else email2 end
     , case when email3 in (email1,email2) then null else email3 end);