显示字段的值,如果为null,则移至下一个

时间:2017-02-23 13:38:53

标签: sql sql-server

我希望有人可以帮我解决这个问题!我使用我返回的数据填写表格。表格上有一个问题可以有多个答案,Q8ReasonA-Q8ReasonH。我的目标是按顺序显示每个答案,它们之间没有空格。

例如,如果某人通过选择B,F和H回答问题8,我希望它显示:

  1. 问题八? 答案:B,F,H
  2. 现在它显示间隔开(留下空白区域,例如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
    

2 个答案:

答案 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;