SQL第二案例声明关闭第一个案例陈述的专栏

时间:2017-08-04 13:48:46

标签: sql case-when

我正在编写一个带有两个Case When语句的查询,第二个使用第一个的状态来确定该值。但是,我在第二个语句中收到无效的列错误。有谁知道解决这个问题的简单解决方案?谢谢!

select 
    a.ID
    ,ss.Date
    ,ss.Name
    ,ss.Payload
    ,case when statusdescription = 'Bad Request' then 'Not Resolved' Else 'Resolved' End as [Error Status] 
    ,case when 
    [Error Status] = 'Not Resolved' --Invalid Column issue occurring with [Error Status] here
    then 'No Resolution' Else a.Date End as [Date],
    ,GETDATE() [Insert Date]

from #Errors a
join Table1 ss on a.id = ss.Id and a.Date = ss.Date 
order by a.Date desc

2 个答案:

答案 0 :(得分:1)

我会将第一个case表达式嵌套在第二个case表达式中。

select 
a.ID
,ss.Date
,ss.Name
,ss.Payload
,case when statusdescription = 'Bad Request' then 'Not Resolved' Else 'Resolved' End as [Error Status] 
,case when 
case when statusdescription = 'Bad Request' then 'Not Resolved' Else 'Resolved' End = 'Not Resolved' --Invalid Column issue occurring with [Error Status] here
then 'No Resolution' Else a.Date End as [Date],
,GETDATE() [Insert Date]

from #Errors a
join Table1 ss on a.id = ss.Id and a.Date = ss.Date 
order by a.Date desc

答案 1 :(得分:0)

在第二个CASE表达式中,您可以再次检查statusdescription的值:

SELECT 
    a.ID,
    ss.Date,
    ss.Name,
    ss.Payload,
    CASE WHEN statusdescription = 'Bad Request'
         THEN 'Not Resolved' ELSE 'Resolved' END AS [Error Status], 
    CASE WHEN statusdescription = 'Bad Request'
         THEN 'No Resolution' ELSE a.Date END AS [Date],
    GETDATE() AS [Insert Date]
FROM #Errors a
INNER JOIN Table1 ss
    ON a.id   = ss.Id   AND
       a.Date = ss.Date 
ORDER BY a.Date DESC

请注意,如果此查询未运行,您可能需要将a.Date转换为第二个CASE表达式中的文本。