case语句中的嵌套子查询返回null

时间:2018-07-18 20:42:33

标签: sql

我正在尝试运行一个嵌套的sql子查询,如果datetime列中的year值不是1799,则从原始表返回一个值,如果该值是1799,则从另一个表的另一列返回最大值。知道我可能在做一些愚蠢的事情,但是当我应该获取日期时,我仅在'logofftime'列中获取NULL。这是我的代码的简单版本:

 SELECT 
 CASE WHEN year(us.logofftime) = '1799' 
 THEN
                (SELECT max(ua.time)
                FROM useractivity ua
                WHERE ua.usersessionid = us.usersessionid)
        ELSE us.logofftime
        END) AS logofftime,
                    us.operatingsystem, us.country, 
                    us.source, us.logoffmethod 
FROM    UserSession us
WHERE us.logontime > '2017-07-01'
AND us.clientid = '12455';

编辑:我已经将最后两行添加到查询中。

1 个答案:

答案 0 :(得分:0)

NULL必须具有许多logofftime值-如果该值为NULL,则结果为NULL

因此,也许您也打算替换这些值:

SELECT (CASE WHEN year(us.logofftime) = 1799 OR us.logofftime IS NULL
             THEN (SELECT max(ua.time)
                   FROM useractivity ua
                   WHERE ua.usersessionid = us.usersessionid
                  )
             ELSE us.logofftime
        END) AS logofftime,
      us.operatingsystem, us.country, 
       us.source, us.logoffmethod 
FROM UserSession us;