子查询中的空值

时间:2017-12-13 10:59:55

标签: sql tsql

我有子查询,其中CompletedDate具有空值我需要添加空值我的输出非空值。

       select * from Crew c
 where 

 a.CrewDate > '2016/12/22 00:00:00'  
   and ActionTypeID = 20
 ---  and objectid = 73658
  AND CrewDate IN (SELECT MAX(CrewDate) FROM Crew cc WHERE c.ObjectID = 
  cc.ObjectID
   AND cc.crewTypeID = 20
    )
 **AND A.CompletedDate IN  (SELECT MAX(CompletedDate)   FROM crew cc WHERE 
 c.ObjectID = cc.ObjectID  
AND AA.ActionTypeID = 20**
 )
   order by ObjectID

oBJECTid     CompletedDate               Createddate
1445209     2017-01-04 09:36:30          2016-12-22 00:00:03
3145514     2017-01-30 15:43:02          2016-12-22 00:00:03
2778154     NULL                         2016-12-22 00:00:03
3025853     2017-01-30 15:43:02          2016-12-22 00:00:03
2342785     2017-03-03 12:02:17          2016-12-22 00:00:03
3113524     NULL                         2016-12-22 08:04:58
3198917     2017-08-16 07:38:29          2016-12-22 08:06:08
1245218     NULL                         2016-12-22 08:12:20
3433585     NULL                         2016-12-22 08:14:35

目前我的查询取出Null值,但我需要输出

中的空值

1 个答案:

答案 0 :(得分:0)

如果我理解您的问题,那么您需要使用LEFT JOIN子查询而不是IN子查询

请查看下一个SQL代码:

SELECT
    c.ObjectID,
    cc.MaxCrewDate,
    cd.MaxCompletedDate
FROM Crew c
LEFT JOIN
(
    SELECT
        cc.ObjectID
        MAX(cc.CrewDate) AS MaxCrewDate
    FROM Crew cc
    WHERE cc.crewTypeID = 20
    GROUP BY cc.ObjectID
) AS cc ON cc.ObjectID = c.ObjectID
LEFT JOIN
(
    SELECT
        cd.ObjectID,
        MAX(CompletedDate) AS MaxCompletedDate
    FROM Crew cd
    WHERE cd.ActionTypeID = 20
    GROUP BY cd.ObjectID
) AS cd ON cd.ObjectID = c.ObjectID