基于一列中的值拆分(复制行)SQL表

时间:2013-04-05 15:32:16

标签: sql-server split multiple-value

我有一个表,它是导出的结果,其列和值如下所示

Name   Aliases          Ranks
Ben    BenA BenB BenC   1 5 3  
Jerry  JerryA JerryB    7 3 

别名和等级由一个字符分隔(在本例中为CHAR(10)),它们具有相同数量的条目。但每个名字可能有不同数量的别名(因此排名)。

我想写一个SQL查询给我下面的表

Name   Alias     Rank
Ben    BenA      1      
Ben    BenB      5 
Ben    BenC      3
Jerry  JerryA    7
Jerry  JerryB    3 

我该怎么做?

1 个答案:

答案 0 :(得分:2)

with cte as (
    select Name, cast(null as int) as AliasStartPosition, cast(0 as int) as AliasEndPosition, Aliases + ' ' as Aliases, cast(null as int) as RankStartPosition, cast(0 as int) as RankEndPosition, Ranks + ' ' as Ranks
    from (
        values ('Ben', 'BenA BenB BenC', '1 5 3'),
               ('Jerry', 'JerryA JerryB', '7 3')
    ) t (Name, Aliases, Ranks)

    union all

    select Name, AliasEndPosition + 1, charindex(' ', Aliases, AliasEndPosition + 1), Aliases, RankEndPosition + 1, charindex(' ', Ranks, RankEndPosition + 1), Ranks
    from cte
    where charindex(' ', Aliases, AliasEndPosition + 1) != 0
)
select Name, substring(Aliases, AliasStartPosition, AliasEndPosition - AliasStartPosition) as Alias, substring(Ranks, RankStartPosition, RankEndPosition - RankStartPosition) as Rank 
from cte
where AliasStartPosition is not null