我正在使用SQL Server 2014
,并且我有一个表(t1),该表具有名为Rank的列(nvarchar
类型)。
下面是该列的摘录:
Rank
#1 of 200 lodges in France
#2 of 200 lodges in France
...
#175 of 200 lodges in France
我想写一个SELECT语句,它将给我以下输出:
Rank Rank2 Type Country
#1 of 200 lodges in France 1 lodges France
#2 of 200 lodges in France 2 lodges France
#175 of 200 lodges in France 175 lodges France
...
我已经尝试使用此处提供的解决方案,但是我坚持将其转换为符合我的要求的方法:Extract data between delimeter in Nvarchar field
如何使用T-SQL做到这一点?
这是解决您问题的一种方法,它使用字符串分隔符和条件聚合
DECLARE @t1 TABLE ([Rank] NVARCHAR(100))
INSERT INTO @t1 ([Rank])
VALUES ('#1 of 200 lodges in France'), ('#2 of 200 lodges in France'), ('#175 of 200 lodges in France')
SELECT
T.[Rank]
,Rank2 = MAX(CASE WHEN S.ItemNumber = 1 THEN CONVERT(INT,S.[Item]) END)
,[Type] = MAX(CASE WHEN S.ItemNumber = 4 THEN S.[Item] END)
,[Country] = MAX(CASE WHEN S.ItemNumber = 6 THEN S.[Item] END)
FROM
@t1 T
CROSS APPLY dbo.DelimitedSplit8K(REPLACE(T.[Rank], '#', ''), ' ') S
GROUP BY
T.[Rank]
ORDER BY
Rank2
但是,这种方法存在局限性,因为假设Type
和Country
仅是一个单词