[英]Removing all records where one condition is met
我有一张如下表:
ID | 部分 | 是_否 |
---|---|---|
EE_1 | 秒_21 | 是 |
EE_1 | 秒_23 | N |
EE_1 | 秒_22 | N |
EE_2 | 秒_21 | N |
我正在寻找一种方法来仅返回“Yes_no”列中没有“Y”的 ID。 所需的输出如下:
ID | 部分 | 是_否 |
---|---|---|
EE_2 | 秒_21 | N |
我认为这就是你想要的:
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
窗口函数通常是这种事情最快的
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;
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.