在SQL Server中筛选多行

时间:2018-05-26 06:10:34

标签: sql-server rowfilter

这是我的表:

ori table

filteredID是将对其进行过滤的条件。但是,如果一行符合条件,我想删除具有相同staffID的所有行。 例如,如果filteredID设置为50或88.我想过滤所有“james”行。

所以我的输出将是:

output table

无法想出一个优雅的方法来解决这个问题。

3 个答案:

答案 0 :(得分:1)

实现此结果的最简单方法是在where子句

中使用'not in'运算符
select 
    staffID, Name 
from 
    Staff 
where 
    staffID not in (select staffID from Staff where filteredID = 50) 
order by 
    staffID;

答案 1 :(得分:1)

这很容易:

declare @my_table table (
  filteredID int,
  staffID int,
  Name varchar(30)
);

insert into @my_table values
  (50, 205, 'james'),
  (88, 205, 'james'),
  (57, 16371, 'jake'),
  (55, 16371, 'jake'),
  (83, 20817, 'jane'),
  (87, 20924, 'jason'),
  (49, 21074, 'jackson'),
  (42, NULL, 'Foo'),
  (170, NULL, 'Goo');

declare @filteredID int = 50;

delete from @my_table
where staffID in (
  select staffID
  from @my_table
  where filteredID = @filteredID
);

select staffID, Name from @my_table;

答案 2 :(得分:0)

假设staffID是一个不可为空的列,您只需通过子查询实现它

DECLARE @filteredID INT
SET @filteredID = 50 --Or another value

DELETE FROM TABLE_NAME
WHERE
(
    staffID IN (SELECT staffID FROM TABLE_NAME WHERE filteredID =@filteredId)
);

SELECT * FROM TABLE_NAME