案例当存在查询不起作用时

时间:2016-04-18 05:40:25

标签: sql sql-server case

我在Microsoft SQL Server中尝试这个:

SELECT DISTINCT 
    a.InteractionID, 
    a.Program, 
    a.[Client Name],
    CASE 
        WHEN EXISTS (
            SELECT * 
            FROM [Interaction Behaviors] 
            JOIN Behaviors 
                ON [Interaction Behaviors].BehaviorID = Behaviors.BehaviorID
            JOIN Interactions
                ON Interactions.InteractionID = [Interaction Behaviors].InteractionID 
            WHERE 
                [Interaction Behaviors].InteractionID = Interactions.InteractionID 
                AND Behaviors.BehaviorID = 1
            ) 
                THEN 1 
        ELSE 0 
        END AS 'Alcohol/Drug Use By Client',
    CASE 
        WHEN EXISTS (
            SELECT * 
            FROM [Interaction Behaviors] JOIN 
            Behaviors 
                ON [Interaction Behaviors].BehaviorID = Behaviors.BehaviorID 
            JOIN Interactions 
                ON Interactions.InteractionID = [Interaction Behaviors].InteractionID 
            WHERE 
                [Interaction Behaviors].InteractionID = Interactions.InteractionID
                AND Behaviors.BehaviorID = 5
            ) 
                THEN Behavior 
        ELSE '' 
    END AS 'Allegation--Text', 
    c.InterventionID,
    d.Intervention ASIntervention_Name  
FROM (
    (
        [Interactions Query] AS a
        INNER JOIN  [Interaction Interventions] AS c 
            ON a.InteractionID = c.InteractionID
    )
LEFT JOIN Interventions AS d 
    ON c.InterventionID = d.InterventionID

第一个Case语句执行正常。

问题出在第二个Cas声明中,我不想要1或0而是实际文本。

对于那个,我收到一条错误消息:

  

消息207,级别16,状态1,行19无效的列名称'行为'

Behavior[Interaction Behaviors]表中的一列。

我知道我需要在from语句中显式加入[Interaction Behaviors]表。但是,这样做会给我奇怪的重复行,所以我需要在Case中处理它。

感谢您的时间!

1 个答案:

答案 0 :(得分:1)

使用以下代码替换行为

angular.js