[英]Select sub string from column based on another column in sql server
I'm trying to get sub string from Country column, based on UserCountry column. 我试图从基于UserCountry列的Country列中获取子字符串。
This is my current output, Based on my query. 这是我当前的输出,基于我的查询。
Now what I want is, If userCountry column value is Singapore then In country column should have only Singapore . 现在我想要的是,如果userCountry列的值是Singapore,那么In country列中应该只有Singapore 。
So My expected output in country column for these 2 result should be 所以我在这两个结果的国家栏中的预期输出应为
Country column have ,
separated value. 国家栏有
,
分隔值。
This is my query 这是我的查询
select PU.Email,PUC.DisplayName UserCountry
,STUFF((SELECT ',' + IIF(C.DisplayName IS NOT NULL,C.DisplayName,CTC.TargetingId)
FROM CampaignTargeting CTC
LEFT JOIN Country C On CTC.TargetingId = C.Id
WHERE CTC.CampaignId =Camp.Id and CTC.TypeName='Country'
FOR XML PATH('')), 1, 1, '') AS Country
,STUFF((SELECT ',' + IIF(P.DisplayName IS NOT NULL, P.DisplayName,CTP.TargetingId)
FROM CampaignTargeting CTP
LEFT JOIN Profession P On CTP.TargetingId = P.Id
WHERE CTP.CampaignId =Camp.Id and CTP.TypeName='Profession'
FOR XML PATH('')), 1, 1, '') AS Profession
,STUFF((SELECT ',' + IIF(S.DisplayName IS NOT NULL, S.DisplayName,CTS.TargetingId)
FROM CampaignTargeting CTS
LEFT JOIN Specialty S On CTS.TargetingId = S.Id
WHERE CTS.CampaignId =Camp.Id and CTS.TypeName='Specialty'
FOR XML PATH('')), 1, 1, '') AS Specialty
,STUFF((SELECT ',' + IIF(SS.DisplayName IS NOT NULL,SS.DisplayName,CTSS.TargetingId)
FROM CampaignTargeting CTSS
LEFT JOIN SubSpecialty SS On CTSS.TargetingId = SS.Id
WHERE CTSS.CampaignId =Camp.Id and CTSS.TypeName='SubSpecialty'
FOR XML PATH('')), 1, 1, '') AS SubSpecialty
FROM Campaign Camp
LEFT JOIN PointsTransaction PT ON PT.ReferenceId=Camp.Id and PT.Points > 0
LEFT JOIN PointUser PU ON PU.Id=PT.PointUserId
LEFT JOIN Country PUC on PU.CountryId=PUC.Id
WHERE Camp.Id='8bd948c9-a597-480b-8772-815f2b31c850'
GROUP BY Camp.Id,PU.Email,PUC.DisplayName
I'm using MS SQL server 2012. 我正在使用MS SQL Server 2012。
Instead of finding the substring, you could directly use the UserCountry column value in Country column, if both need to be the same. 如果两者都需要相同,则可以直接在“国家/地区”列中使用UserCountry列的值,而不是查找子字符串。 Hope it helps.
希望能帮助到你。
Just use a case
statement: 只需使用一个
case
语句:
SELECT . . . ,
(CASE WHEN PUC.DisplayName = 'Singapore' THEN 'Singapore'
ELSE STUFF((SELECT ',' + IIF(C.DisplayName IS NOT NULL,C.DisplayName, CTC.TargetingId)
FROM CampaignTargeting CTC LEFT JOIN
Country C
ON CTC.TargetingId = C.Id
WHERE CTC.CampaignId = Camp.Id and CTC.TypeName = 'Country'
FOR XML PATH('')
), 1, 1, ''
)
END) AS Country,
. . .
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.