简体   繁体   中英

Concatenate Fields in Order - SQL Server

I have a table consisting of 5 integer ids, and would like to add a column which takes these ids, orders them and concatenates them in some fashion similar to below.

id1       id2       id3      id4       id5      new_col
364       53        468      184       469      /53/184/364/468/469/
48        47        49       364       266      /47/48/49/266/364/

Is there a function which will make performing the ordering quicker and easier? God forbid if I have to code up the ordering by hand.

You could also use XML PATH ( Online Demo )

SELECT id1,
       id2,
       id3,
       id4,
       id5,
       new_col = CONCAT('/', ids)
FROM   YourTable
       CROSS APPLY (SELECT CONCAT(id, '/')
                    FROM   (VALUES (id1),
                                   (id2),
                                   (id3),
                                   (id4),
                                   (id5)) V(id)
                    ORDER  BY id
                    FOR XML PATH('')) C(ids) 

This is a real pain in SQL Server. Here is one method:

select t.*, v.ids
from t outer apply
     (select ('/' + max(case when seqnum = 1 then id end) +
              '/' + max(case when seqnum = 2 then id end) +
              '/' + max(case when seqnum = 3 then id end) +
              '/' + max(case when seqnum = 4 then id end) +
              '/' + max(case when seqnum = 5 then id end) +
              '/') as ids
      from (select id, row_number() over (order by id) as seqnum
            from (values(id1), (id2), (id3), (id4), (id5)) v(id)
           ) v
     ) v;

I hope there is some id column already in real table.

declare @data table (c1 int, c2 int, c3 int, c4 int, c5 int)

insert into @data (c1, c2, c3, c4, c5)
values
(364, 53, 468, 184, 469),
(48, 47, 49, 364, 266)


;with NumberedRows as
(
  select
    d.c1, d.c2, d.c3, d.c4, d.c5, 
    row_number() over(order by (select 1)) rn
  from @data d
)
select
  rn, r.c1, r.c2, r.c3, r.c4, r.c5,
  stuff(
    (
      select concat('/', p.num)
      from 
      (
        select rr.c1, rr.c2, rr.c3, rr.c4, rr.c5
        from NumberedRows rr
        where rr.rn = r.rn
      ) rr
      unpivot (num for cols in (c1, c2, c3, c4, c5)) p
      order by p.num
      for xml path(''), type
    ).value('.', 'varchar(max)')
  , 1, 1, '') value_list
from NumberedRows r
order by r.rn

在此输入图像描述

And look how over-complicated it looks against that VALUES (), () trick by @Martin and @Gordon. Yep.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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