在case语句中连接多个列

时间:2016-12-13 18:00:55

标签: sql-server

有一个查询,我必须在case语句中连接12列。如果是2或3,它会更容易。为了更清楚,这是我的疑问:

SELECT column1 
  ,column2
  ,effet_secondaire_desc = CASE WHEN [symp01] = 'y' THEN 'Pedi apeti'
                                WHEN [symp02] = 'y' THEN 'Ke plen'
                                WHEN [symp03] = 'y' THEN 'Zye jon'
                                WHEN [symp04] = 'y' THEN 'Dyare'
                                WHEN [symp05] = 'y' THEN 'Ko grate'
                                WHEN [symp06] = 'y' THEN 'Lafyev ak frison'
                                WHEN [symp07] = 'y' THEN 'Ko fe mal ak jwenti fe mal'
                                WHEN [symp08] = 'y' THEN 'Pikotman'
                                WHEN [symp09] = 'y' THEN 'Fatig'
                                WHEN [symp10] = 'y' THEN 'Tet vire/vetij'
                                WHEN [symp11] = 'y' THEN 'Vant fe mal'
                                WHEN [symp12] = 'y' THEN [symp12_desc] 
                                ELSE '~'
                            END
             .....
             ,columnx
FROM MyTable

[symp01] ... [symp12]是我要连接的12列。因此,effet_secondaire_desc的价值应该是这样的' Pedi apeti,Ko grate,Lafyev ak frison,...'。

有人可以帮我吗? 提前谢谢。

2 个答案:

答案 0 :(得分:0)

这样的事情?:

SELECT
...
CASE WHEN [symp01] = 'y' THEN ', Pedi apeti' ELSE '' END
+ CASE WHEN [symp02] = 'y' THEN ', Ke plen' ELSE '' END
+ ...
END

然后将其包含在某个逻辑中以删除第一个逗号和空格。

答案 1 :(得分:0)

select 
    column1 
  , column2
  , effet_secondaire_desc = isnull(nullif(stuff(
     case when [symp01] = 'y' then ', Pedi apeti'                  else '' end
    +case when [symp02] = 'y' then ', Ke plen'                     else '' end
    +case when [symp03] = 'y' then ', Zye jon'                     else '' end
    +case when [symp04] = 'y' then ', Dyare'                       else '' end
    +case when [symp05] = 'y' then ', Ko grate'                    else '' end
    +case when [symp06] = 'y' then ', Lafyev ak frison'            else '' end
    +case when [symp07] = 'y' then ', Ko fe mal ak jwenti fe mal'  else '' end
    +case when [symp08] = 'y' then ', Pikotman'                    else '' end
    +case when [symp09] = 'y' then ', Fatig'                       else '' end
    +case when [symp10] = 'y' then ', Tet vire/vetij'              else '' end
    +case when [symp11] = 'y' then ', Vant fe mal'                 else '' end
    +case when [symp12] = 'y' then ', '+[symp12_desc]              else '' end
    ,1,2,''),''),'~')
  , columnx
from mytable