合并两个STRING_SPLIT

时间:2017-09-21 13:38:11

标签: sql sql-server tsql sql-server-2016

考虑以下问题: 我有两个用于拆分的字符串:

STR1 = 'b;a;c;d;e'

STR2 = '3;1;4;2;5'

我想根据它们的索引拆分和合并这两个字符串,结果是:

b -> 3
a -> 1
c -> 4
d -> 2
e -> 5

我尝试使用STRING_SPLIT,但order by对它们进行了排序。

SELECT A.VALUE, B.VALUE FROM (
    SELECT VALUE, ROW_NUMBER() OVER(ORDER BY VALUE) AS RW
    FROM STRING_SPLIT('b;a;c;d;e', ';')
) A
INNER JOIN (
    SELECT VALUE, ROW_NUMBER() OVER(ORDER BY VALUE) AS RW
    FROM STRING_SPLIT('3;1;4;2;5', ';')
) B
ON A.RW = B.RW

这会产生以下结果:

a   1
b   2
c   3
d   4
e   5

4 个答案:

答案 0 :(得分:4)

也许是这样的?

declare @STR1 varchar(64) = 'b;a;c;d;e'

declare @STR2 varchar(64)  = '3;1;4;2;5'

;with cte as(
select
    value
    ,RN = row_number() over (order by (select null))
from
    STRING_SPLIT(@STR1,';')),

cte2 as(
select
    value
    ,RN = row_number() over (order by (select null))
from
    STRING_SPLIT(@STR2,';'))

select
    c.value + d.value
from
    cte c
    inner join 
    cte2 d on c.RN = d.RN

答案 1 :(得分:2)

STRING_SPLIT不会返回行号。它不适用于您的要求。

我在这里使用Jeff的DelimitedSplit8K http://www.sqlservercentral.com/articles/Tally+Table/72993/

declare @STR1 varchar(20) = 'b;a;c;d;e'

declare @STR2 varchar(20) = '3;1;4;2;5'

select  s1.Item , s2.Item
from    DelimitedSplit8K (@STR1, ';') s1
    inner join DelimitedSplit8K (@STR2, ';') s2 on  s1.ItemNumber   = s2.ItemNumber
order by s1.ItemNumber

答案 2 :(得分:0)

另一种不依赖STRING_SPLIT()函数的方法:

DECLARE @xml       AS XML, 
        @xml2      AS XML, 
        @str       AS VARCHAR(100), 
        @str2      AS VARCHAR(100), 
        @delimiter AS VARCHAR(10) 

SET @str='b;a;c;d;e' 
SET @str2 = '3;1;4;2;5' 
SET @delimiter =';' 
SET @xml = Cast(( '<X>' + Replace(@str, @delimiter, '</X><X>') 
                  + '</X>' ) AS XML) 
SET @xml2 = Cast(( '<X>' + Replace(@str2, @delimiter, '</X><X>') 
                   + '</X>' ) AS XML) 

SELECT a.value, 
       b.value 
FROM   (SELECT n.value('.', 'varchar(10)') AS value, 
               Row_number() 
                 OVER ( 
                   ORDER BY (SELECT 100))  AS SNO 
        FROM   @xml.nodes('X') AS T(n))a 
       INNER JOIN (SELECT n.value('.', 'varchar(10)') AS value, 
                          Row_number() 
                            OVER ( 
                              ORDER BY (SELECT 100))  AS SNO 
                   FROM   @xml2.nodes('X') AS T(n))b 
               ON a.sno = b.sno 

答案 3 :(得分:0)

我喜欢你尝试的解决方案。如果您php_value为文字值而非order by

,则此方法有效
VALUE