使用NOT IN发出NULL值

时间:2017-11-10 16:10:18

标签: sql-server

我有一个查询,我试图删除所有记录,如果练习和实体的组合只显示一次,并且一个记录的状态为Terminated或Withdrawn,那么我希望它被删除。如果练习/实体有多个记录,并且其中至少有一个记录的状态不是Terminated / Withdrawn,那么我想保留其他记录。我写了一个执行此操作的查询,如下所示。

但是,我遇到的问题是查询正在删除NULL记录。我知道这是因为存在/ NOT IN子句,其中NULL<> (终止,撤回)评估为UNKNOWN。

我尝试以相反的方式编写查询,使用NOT EXISTS / IN,但删除了数千条其他记录。有谁知道在这种情况下如何包含NULL值?

const browserNotification = new Notification(title, options);

browserNotification.onshow = () => this.props.sendTracking('in-app-chat-notification-start');

browserNotification.onclick = event => {
  const notification = event.target;

  this.props.router.push(notification.data.url.split('.com')[1]);
  this.props.sendTracking('in-app-chat-notification-complete');

  notification.close();
};

2 个答案:

答案 0 :(得分:2)

我宁愿使用t2.statusname IS NULL,因此优化器仍然可以使用任何索引。

select *,
       ROW_NUMBER()over(partition by entity, statusname order by entity) as rn
from @tab t1
where exists(select 1
             from @tab t2
             where t1.practice = t2.practice
               and t1.entity= t2.entity
               and t1.assignedto = t2.assignedto
               and (t2.statusname IS NULL OR
                    t2.statusname not in ('Withdrawn', 'Terminated')
                   )
            );

答案 1 :(得分:1)

您可以将ISNULL与虚拟值一起使用:

select *,
ROW_NUMBER()over(partition by entity, statusname order by entity) as rn
from @tab t1
where exists(select *
             from @tab t2
             where t1.practice = t2.practice
             and t1.entity= t2.entity
             and t1.assignedto = t2.assignedto
             and ISNULL(t2.statusname, '@@@') 
                 not in( 'Withdrawn', 'Terminated'));

<强> Rextester.com