删除满足一个条件的所有记录
Removing all records where one condition is met
我有一个 table 如下所示:
ID
section
Yes_no
EE_1
sec_21
Y
EE_1
sec_23
N
EE_1
sec_22
N
EE_2
sec_21
N
我正在寻找一种方法 return 只有在“Yes_no”列中没有 'Y' 的 ID。所需输出如下:
ID
section
Yes_no
EE_2
sec_21
N
Select * from table_X where ID not in (Select ID from table_X where Yes_no ='Y')
我想这就是你想要的:
create table MyTable(
ID varchar(10),
section varchar(50),
Yes_no varchar(1)
)
insert into MyTable values
('EE_1','sec_21','Y'),
('EE_1','sec_23','N'),
('EE_1','sec_22','N'),
('EE_2','sec_21','N')
select *
from MyTable t1
where t1.Yes_no = 'N' and not exists
(select * from MyTable t2 where t2.ID = t1.ID and t2.Yes_no = 'Y')
DBFiddler: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=0b24198e227588df323c579facd37153
Window 对于这种事情,函数通常是最快的
SELECT
t.ID,
t.section,
t.Yes_no
FROM (
SELECT *,
CountY = COUNT(CASE WHEN t.Yes_no = 'Y' THEN 1 END) OVER (PARTITION BY t.ID)
FROM YourTable t
) t
WHERE CountY = 0;
您可以使用 exists
关键字来执行此查询,因为 exists
的性能优于 in
。
select *
from Table t
where t.Yes_no = 'N' and not exists
(select * from Table b where b.ID = b.ID and b.Yes_no = 'Y')
我有一个 table 如下所示:
ID | section | Yes_no |
---|---|---|
EE_1 | sec_21 | Y |
EE_1 | sec_23 | N |
EE_1 | sec_22 | N |
EE_2 | sec_21 | N |
我正在寻找一种方法 return 只有在“Yes_no”列中没有 'Y' 的 ID。所需输出如下:
ID | section | Yes_no |
---|---|---|
EE_2 | sec_21 | N |
Select * from table_X where ID not in (Select ID from table_X where Yes_no ='Y')
我想这就是你想要的:
create table MyTable(
ID varchar(10),
section varchar(50),
Yes_no varchar(1)
)
insert into MyTable values
('EE_1','sec_21','Y'),
('EE_1','sec_23','N'),
('EE_1','sec_22','N'),
('EE_2','sec_21','N')
select *
from MyTable t1
where t1.Yes_no = 'N' and not exists
(select * from MyTable t2 where t2.ID = t1.ID and t2.Yes_no = 'Y')
DBFiddler: https://dbfiddle.uk/?rdbms=sqlserver_2019&fiddle=0b24198e227588df323c579facd37153
Window 对于这种事情,函数通常是最快的
SELECT
t.ID,
t.section,
t.Yes_no
FROM (
SELECT *,
CountY = COUNT(CASE WHEN t.Yes_no = 'Y' THEN 1 END) OVER (PARTITION BY t.ID)
FROM YourTable t
) t
WHERE CountY = 0;
您可以使用 exists
关键字来执行此查询,因为 exists
的性能优于 in
。
select *
from Table t
where t.Yes_no = 'N' and not exists
(select * from Table b where b.ID = b.ID and b.Yes_no = 'Y')