0

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

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 

我怎样才能做到这一点?

4

1 回答 1

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
于 2013-04-05T16:27:57.060 回答