在 SQL 复合体中切换 NULL 值

switch NULL values in SQL complex

嘿,我有这个查询:

 select
   MAX(CASE WHEN ConsultationStatus = 1 THEN AnswerDate END) AS FinalAnswerDate,
   MAX(CASE WHEN ConsultationStatus = 2 THEN AnswerDate END) AS StartAnswerDate
from some_table

现在,我希望当 StartAnswerDate 为 NULL 时,它会复制 FinalAnswerDate 单元格中的任何内容。

这个想法是,有时会有一个没有开始回答日期的最终回答日期,所以现在它显示最终回答日期(时间戳),而在开始日期它显示 NULL。

当没有开始日期而只有结束日期时,我希望开始日期与最终日期显示相同(因为开始和结束的时间是在同一时间)。

基本上,将 NULL 值切换到附近单元格中的值..

现在显示:

FinalAnswerDate                     StartAnswerDate        
------------------------------------------------------------------
 2022-05-03 10:00:00                NULL                    (*because there is no start answer date, only final)
 2022-05-03 09:09:00                2022-05-03 08:34:00     (ex of start answer date different from final)

我想要的:

  FinalAnswerDate                     StartAnswerDate        
------------------------------------------------------------------
 2022-05-03 10:00:00                2022-05-03 10:00:00   (same date as final)                    
 2022-05-03 09:09:00                2022-05-03 08:34:00    

这个怎么样:

SELECT
    FinalAnswerDate,
    CASE WHEN StartAnswerDate IS NOT NULL THEN StartAnswerDate ELSE FinalAnswerDate END AS StartAnswerDate
FROM (SELECT
    MAX(CASE WHEN ConsultationStatus = 1 THEN AnswerDate END) AS FinalAnswerDate,
    MAX(CASE WHEN ConsultationStatus = 2 THEN AnswerDate END) AS StartAnswerDate
FROM some_table) AS T

或者没有子选择,但这可能表现不佳:

SELECT
   MAX(CASE WHEN ConsultationStatus = 1 THEN AnswerDate END) AS FinalAnswerDate,
   CASE WHEN (MAX(CASE WHEN ConsultationStatus = 2 THEN AnswerDate END) IS NOT NULL) THEN MAX(CASE WHEN ConsultationStatus = 2 THEN AnswerDate END) ELSE (MAX(CASE WHEN ConsultationStatus = 1 THEN AnswerDate END)) END AS StartAnswerDate
FROM some_table

也许有更好的方法。