Order before CONCAT_WS

风流意气都作罢 提交于 2019-12-06 21:31:28

The following should work, if the values are indeed NULL and not blank:

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

The reference is here:

CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.

To handle ordering, I would go for:

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

This will filter out any id that doesn't have a phone number.

You can also do this with a giant case statement, although that seems something of a nightmare:

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

This is more efficient. It is feasible for 3 phone numbers. I wouldn't want to deal with, say, five of them.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!