Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/visual-studio-code/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 如何在同一个表中检索具有相同列但具有不同条件的行?_Sql Server - Fatal编程技术网

Sql server 如何在同一个表中检索具有相同列但具有不同条件的行?

Sql server 如何在同一个表中检索具有相同列但具有不同条件的行?,sql-server,Sql Server,我有一个表,它将为每个更新添加条目,这里发生的每个更新都是我的数据 ID EmpId ischange 1 100 0 2 100 1 3 101 0 4 101 0 5 101 0 我需要的是,我希望有一个查询,它将返回ischange值为0,如果至少有1名员工拥有1,那么我不希望显示该记录 我只需要id为101的记录简单易懂的方式: select * from mytable where

我有一个表,它将为每个更新添加条目,这里发生的每个更新都是我的数据

ID  EmpId ischange
1     100       0
2     100       1
3     101       0
4     101       0
5     101       0 
我需要的是,我希望有一个查询,它将返回ischange值为0,如果至少有1名员工拥有1,那么我不希望显示该记录


我只需要id为101的记录

简单易懂的方式:

select * from mytable
where EmpId not in (
    select EmpId from mytable
    where ischange = 1)
性能更高的方法(假设
EmpId
上有索引):


选择总行数等于
isChange
is
0
计数的行

查询

select [EmpId] from [tableName]
group by [EmpId]
having sum(case [ischange] when 0 then 1 else 0 end) = count([EmpId]);
select * from [tableName] as [t1]
where not exists(
    select 1 from [tableName] as [t2]
    where [t1].[EmpId] = [t2].[EmpId]
    and [ischange] = 1
);
或者,如果你想要整行,那么

查询

select [EmpId] from [tableName]
group by [EmpId]
having sum(case [ischange] when 0 then 1 else 0 end) = count([EmpId]);
select * from [tableName] as [t1]
where not exists(
    select 1 from [tableName] as [t2]
    where [t1].[EmpId] = [t2].[EmpId]
    and [ischange] = 1
);

或者更有效的方式:

select * from myTable t1
where not exists 
 (select * from myTable t2 
  where t1.empId=t2.empId and t2.ischange=1);

预期的结果?到目前为止你尝试了什么?任何东西如果没有,则查找
存在
,尝试一些方法,如果不起作用,请在尝试后发布。最好将示例数据作为+。请将您的问题包括在内,您当前的尝试和您想要的结果。有关更多详细信息,OP需要整行。您还可以使用一个
不存在的
,根据数据的不同,它可能运行良好。请小心
中的
(不)。如果任何行的
EmpID
值为
NULL
,您将获得意外行为。@iamdave not exists需要一个相关的子查询,它的性能将永远不会更好。如果优化者重写查询以删除它,那么它最多也会执行相同的操作。通常,它在所有选项中表现最差。@Bohemian你确定吗?有传唤吗?@larnu我肯定。你可以认为我是权威人士。