SQL 第一个案例陈述列中的第二个案例陈述

SQL 2nd Case Statement Off First Case Statement's Column

我正在编写一个包含两个 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

我会将第一个 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

在第二个 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 表达式中的文本。