繁体   English   中英

在CONCAT_WS之前订购

[英]Order before CONCAT_WS

我有一个带有3个Phone列的表,我需要运行一些魔术来尝试获取一些记录,使它们之间的电话号码匹配,问题是Phone number可能位于2条记录之间的不同字段上。

因此,我认为带有3个电话号码的规范字符串应该可以进行比较,问题是规范化过程。 有没有办法做到这一点? 我正在添加一个片段来说明我需要做什么。

表是:

╔═════╦══════════╦══════════╦══════════╗
║ ID  ║  Phone1  ║  Phone2  ║  Phone3  ║
╠═════╬══════════╬══════════╬══════════╣
║ 123 ║ 555-1234 ║ 666-1235 ║          ║
║ 124 ║ 666-1235 ║          ║ 555-1234 ║
║ 125 ║ 555-8520 ║ 777-7410 ║ 444-9999 ║
╚═════╩══════════╩══════════╩══════════╝

我想要的结果是

╔═════╦══════════════════════════════╗
║ ID  ║         ConcatPhones         ║
╠═════╬══════════════════════════════╣
║ 123 ║ 555-1234||666-1235           ║
║ 124 ║ 555-1234||666-1235           ║
║ 125 ║ 444-9999||555-8520||777-7410 ║
╚═════╩══════════════════════════════╝

无论如何,我可以使用CONCAT_WS的简单变体或高效的存储过程来做到这一点吗?

如果值确实为NULL且不为空,则应执行以下操作:

select id,
       concat_ws('||', Phone1, Phone2, Phone3)
from t

参考在这里

CONCAT_WS()不会跳过空字符串。 但是,它会跳过分隔符参数之后的所有NULL值。

为了处理订购,我将寻求:

select id,
       group_concat(phone Separator '||' order by phone) as ConcatPhones
from (select t.id,
             (case when nums.n = 1 then phone1
                   when nums.n = 2 then phone2
                   when nums.n = 3 then phone3
              end) as phone
       from t cross join
            (select 1 as n union all select 2 union all select 3) nums
     ) p
where phone is not null
group by id

这将过滤掉没有电话号码的所有ID。

您也可以通过一个巨大的case声明来做到这一点,尽管这似乎是一场噩梦:

select t.id,
       (case when phone1 < phone2 and phone2 < phone3 then concat_ws('||', phone1, phone2, phone3)
             when phone1 < phone3 and phone3 < phone2 then concat_ws('||', phone1, phone3, phone2)
              . . .  through the remaining 4 permuatiations when all three are present
             when phone1 is null and phone2 < phone3 then concat_ws('||', phone2, phone3)
             . . . through the remaining 5 permutuations when one is NULL
             when phone1 is null and phone2 is null then phone3
              . . . through the remaining 2 permutations when two are NULL
        end) as ConcatPhones
from t

这样更有效。 3个电话号码是可行的。 我不想处理其中的五个问题。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM