简体   繁体   中英

Removing all records where one condition is met

I have a table like below:

ID section Yes_no
EE_1 sec_21 Y
EE_1 sec_23 N
EE_1 sec_22 N
EE_2 sec_21 N

I'm looking for a way to return ONLY IDs where there is NO 'Y' in the "Yes_no" column. Desired output below:

ID section Yes_no
EE_2 sec_21 N

I think this is what you want:

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 functions are usually the fastest for this kind of thing

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;

db<>fiddle

Select * from table_X where ID not in (Select ID from table_X where Yes_no ='Y')

运行示例

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM