将多个列合并为一个时的案例

时间:2013-09-18 18:23:12

标签: sql casting case

我正在尝试创建一个查询,该查询将在视图中占用多个列并将其带入查询中的一列。每列的值需要用' |'分隔。 (管)。

我试过了:

1)(expression1 + '|' + expression2) AS xxxx,但如果一个表达式具有空值,则会使结果为' null'。

2)CAST (expression1 as varchar (10)) + '|' + CAST (expression2 as varchar (10)) AS xxxx,但获得相同的结果。

3)CASE (expression1 is null) then (' ') else (expression1) +'|' + CASE (expression2 is null) then (' ') else (expression2) END AS xxxx,但我在关键字'AS'.

附近收到语法错误

这是使用CASE的完整查询。

SELECT DISTINCT dbo.REG.BUILDING, dbo.REG.CURRENT_STATUS, dbo.REG_CONTACT.LOGIN_ID, dbo.REG.LAST_NAME
, CASE WHEN dbo.View_MYAccess_Period1.CRSGRP1 is null then ' ' else        dbo.View_MYAccess_Period1.CRSGRP1 + ' |' +
  CASE WHEN dbo.View_MYAccess_Period2.CRSGRP2 is null then ' ' else dbo.View_MYAccess_Period2.CRSGRP2
END AS CRSGRP

FROM  dbo.REG_CONTACT RIGHT OUTER JOIN
dbo.REG_STU_CONTACT ON dbo.REG_CONTACT.CONTACT_ID = dbo.REG_STU_CONTACT.CONTACT_ID RIGHT OUTER JOIN 
dbo.REG ON dbo.REG_STU_CONTACT.STUDENT_ID = dbo.REG.STUDENT_ID LEFT OUTER JOIN 
dbo.View_MYAccess_Period1 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period1.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period2 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period2.STUDENT_ID

对这位新手的任何帮助都将不胜感激!

2 个答案:

答案 0 :(得分:1)

使用ISNULL功能,

SELECT DISTINCT dbo.REG.BUILDING, dbo.REG.CURRENT_STATUS, dbo.REG_CONTACT.LOGIN_ID, dbo.REG.LAST_NAME
, ISNULL(dbo.View_MYAccess_Period1.CRSGRP1,' ') + ' |' +
  ISNULL(dbo.View_MYAccess_Period2.CRSGRP2,' ') CRSGRP

FROM  dbo.REG_CONTACT RIGHT OUTER JOIN
dbo.REG_STU_CONTACT ON dbo.REG_CONTACT.CONTACT_ID = dbo.REG_STU_CONTACT.CONTACT_ID RIGHT OUTER JOIN 
dbo.REG ON dbo.REG_STU_CONTACT.STUDENT_ID = dbo.REG.STUDENT_ID LEFT OUTER JOIN 
dbo.View_MYAccess_Period1 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period1.STUDENT_ID LEFT OUTER JOIN
dbo.View_MYAccess_Period2 ON dbo.REG.STUDENT_ID = dbo.View_MYAccess_Period2.STUDENT_ID

答案 1 :(得分:0)

在示例1中,如果表达式为null,则可以使用COALESCE(expression, fallback)函数强制expression返回回退值。 (然后相应地调整其余的逻辑。)

在您的示例3中,您需要另一个END关键字:

CASE
    (expression1 is null) then (' ')
    ELSE (expression1) +'|' +
        CASE (expression2 is null) then (' ') else (expression2) END
END AS xxxx