我希望有人可以帮我解决这个问题!我使用我返回的数据填写表格。表格上有一个问题可以有多个答案,Q8ReasonA-Q8ReasonH。我的目标是按顺序显示每个答案,它们之间没有空格。
例如,如果某人通过选择B,F和H回答问题8,我希望它显示:
现在它显示间隔开(留下空白区域,例如A答案)。这是我的代码的一部分:
SELECT DISTINCT SFA.DOB, SFA.Name, SFA.SupvsrName,
SFA.Question8,MFA.Q8ReasonA, MFA.Q8ReasonB, MFA.Q8ReasonC,
MFA.Q8ReasonD, MFA.Q8ReasonE, MFA.Q8ReasonF, MFA.Q8ReasonG, MFA.Q8ReasonH
FROM SingleFileAnswer SFA
JOIN MultipleFileAnswer MFA on SFA.SupvsrID=MFA.SupvsrID
WHERE SFA.SupvsrID=1234
答案 0 :(得分:0)
您可以CASE
使用STUFF
来生成仅包含非空答案的逗号分隔值:
select distinct SFA.DOB,
SFA.name,
SFA.SupvsrName,
SFA.Question8,
STUFF(
case when MFA.Q8ReasonA is not null then ', A' else '' END +
case when MFA.Q8ReasonB is not null then ', B' else '' END +
case when MFA.Q8ReasonC is not null then ', C' else '' END +
case when MFA.Q8ReasonD is not null then ', D' else '' END +
case when MFA.Q8ReasonE is not null then ', E' else '' END +
case when MFA.Q8ReasonF is not null then ', F' else '' END +
case when MFA.Q8ReasonG is not null then ', G' else '' END +
case when MFA.Q8ReasonH is not null then ', F' else '' END
, 1, 2, '') answers
from SingleFileAnswer SFA
join MultipleFileAnswer MFA on SFA.SupvsrID = MFA.SupvsrID
where SFA.SupvsrID = 1234
如果您想显示实际答案:
select distinct SFA.DOB,
SFA.name,
SFA.SupvsrName,
SFA.Question8,
STUFF(
coalesce(', ' + MFA.Q8ReasonA, '') +
coalesce(', ' + MFA.Q8ReasonB, '') +
coalesce(', ' + MFA.Q8ReasonC, '') +
coalesce(', ' + MFA.Q8ReasonD, '') +
coalesce(', ' + MFA.Q8ReasonE, '') +
coalesce(', ' + MFA.Q8ReasonF, '') +
coalesce(', ' + MFA.Q8ReasonG, '') +
coalesce(', ' + MFA.Q8ReasonH, '')
, 1, 2, '') answers
from SingleFileAnswer SFA
join MultipleFileAnswer MFA on SFA.SupvsrID = MFA.SupvsrID
where SFA.SupvsrID = 1234
答案 1 :(得分:0)
您可以将字符串与concat
函数连接在一起,并使用null
函数检查isnull
值。使用stuff
删除初始逗号和空格(从字符1
开始,并用空字符串2
替换''
个字符):
select distinct
SFA.DOB
,SFA.Name
,SFA.SupvsrName
,SFA.Question8
,MFA.Q8ReasonA
,MFA.Q8ReasonB
,MFA.Q8ReasonC
,MFA.Q8ReasonD
,MFA.Q8ReasonE
,MFA.Q8ReasonF
,MFA.Q8ReasonG
,MFA.Q8ReasonH
,stuff(concat(isnull(', ' + MFA.Q8ReasonA,'')
,isnull(', ' + MFA.Q8ReasonB,'')
,isnull(', ' + MFA.Q8ReasonC,'')
,isnull(', ' + MFA.Q8ReasonD,'')
,isnull(', ' + MFA.Q8ReasonE,'')
,isnull(', ' + MFA.Q8ReasonF,'')
,isnull(', ' + MFA.Q8ReasonG,'')
,isnull(', ' + MFA.Q8ReasonH,'')
)
,1,2,'') as Concatenated
from SingleFileAnswer as SFA
join MultipleFileAnswer as MFA
on SFA.SupvsrID = MFA.SupvsrID
where SFA.SupvsrID = 1234;