Home > database >  How to create an ordered string from multiple columns?
How to create an ordered string from multiple columns?

Time:01-06

If I want to create an ordered string column (C4) given the columns C1, C2, and C3, how can I proceed so?

enter image description here

CodePudding user response:

On on the assumption ssms indicates you're using SQL Server, you can unpivot your columns and use string_agg to concatenate them in order.

An example would be:

with data as (
  select * from (values('Alton', 'Webs', 'James'), ('a', 'b', 'c'),('c', 'b', 'a')
)x(c1,c2,c3))
select *
from data
cross apply(
    select String_Agg(c,'') within group(order by c) as c4
    from(
        values(c1),(c2),(c3)
    )s(c)
)c4;
  • Related