我正在尝试根据UserCountry列从Country列获取子字符串。
这是我当前的输出,基于我的查询。
现在我想要的是,如果userCountry列值为新加坡,那么在国家/地区列中应该只有新加坡。
因此,对于这两个结果,我在国家/地区列中的预期输出应为
国家/地区列的值为,
分隔值。
这是我的查询
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
我正在使用MS SQL server 2012。
答案 0 :(得分:0)
如果两者都需要相同,则可以直接在Country列中使用UserCountry列值,而不是查找子字符串。希望它有所帮助。
答案 1 :(得分:0)
只需使用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,
. . .