如何在以下条件下从Offset Group
列和HedgeId
列中获取值?
SecurityGroupId
列Offset Group
列和HedgeId
列提取的值应仅包含SecurityGroupId
中提到的字符串右侧的剩余字符串。答案 0 :(得分:1)
请使用以下查询,
select
parsename(replace(OffsetGroup,SecurityGroupID,'.'),1) as [Offset Group],
parsename(replace(HedgeID,SecurityGroupID,'.'),1) as [HedgeID]
from @TableName
where OffsetGroup like '%'+SecurityGroupID+'%'
and HedgeID like '%'+SecurityGroupID +'%'
答案 1 :(得分:0)
您可以使用符合Offset Group
条件的行匹配HedgeID
来分割SecurityGroupID
和like
值,然后使用带有XML转换的CTE将数据检索为列:
declare @tmp table(SecurityGroupID varchar(10), OffsetGroup nvarchar(50), HedgeID varchar(50))
insert into @tmp values
('S1G', 'OG139099S1G36', 'HG139099S1G1')
,('S1G', 'OG139099S1G36', 'HG139099S1G2')
,('S1G', 'OG139099S1G36', 'HG139099S1G3')
,('S1G', 'OG139099S1G36', 'HG139099S1G4')
,('S1G', 'OG139099S1G36', 'HG139099S2G4')
,('S1G', 'OG139099S2G36', 'HG13909912G4')
;WITH CTEwithSplittedValues AS
(
select
CAST('<x>' + REPLACE(OffsetGroup, SecurityGroupID,'</x><x>') + '</x>' AS XML) AS Offset_Group
,CAST('<x>' + REPLACE(HedgeID, SecurityGroupID,'</x><x>') + '</x>' AS XML) AS Hedge_ID
from @tmp
where OffsetGroup like '%' + SecurityGroupID + '%'
and HedgeID like '%' + SecurityGroupID + '%'
)
SELECT
Offset_Group.value(N'/x[2]','varchar(50)') AS [Offset Group]
,Hedge_ID.value(N'/x[2]','varchar(50)') AS [HedgeID]
FROM CTEwithSplittedValues;
这是最终输出:
未提取最后两行,因为SecurityGroupID
和Offset Group
中未找到HedgeID
,但只有其中一行。