按顺序连接字段 - SQL Server

时间:2016-07-09 18:56:12

标签: sql sql-server

我有一个由5个整数id组成的表,并且想要添加一个带有这些id的列,命令它们并以类似于下面的方式连接它们。

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/

是否有能够更快更轻松地执行订购的功能?如果我必须手工编码,那么上帝是禁止的。

3 个答案:

答案 0 :(得分:4)

您也可以使用XML PATHOnline 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) 

答案 1 :(得分:3)

这是SQL Server真正的痛苦。这是一种方法:

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;

答案 2 :(得分:1)

我希望实际表格中已有一些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 列。

VALUES (), ()

enter image description here

看看@Martin和@Gordon对echo "<div id='slider'> <ul class='slides'> <li class='slide'> <div class='pic'> <img src= " . $dir . $pic_array[$index] . " /> </div> <div class='caption'> <p id='title'>$titles[$index]</p> <p id='des'>$descriptions[$index]</p> </div> <div class='next'> <i class='fa fa-arrow-right fa-2x'></i> </div> <div class='previous'> <i class='fa fa-arrow-left fa-2x'></i> </div> </li>"; echo "</ul> </div> </html>"; $conn->close(); ?> 伎俩的看法过于复杂。是的。