如何解决如果同一组中存在另一个记录,则忽略该组中的记录
我正在尝试从一组结果中删除一条记录,如果同一组中有一条具有特定值的记录。我试图将我的复杂问题调整为一个简单的例子:
DECLARE @fruits TABLE (type varchar(16),attribute varchar(16))
INSERT INTO @fruits VALUES('orange','juicy');
INSERT INTO @fruits VALUES('orange','seeds');
INSERT INTO @fruits VALUES('orange','pit');
INSERT INTO @fruits VALUES('apple','juicy');
INSERT INTO @fruits VALUES('apple','seeds');
INSERT INTO @fruits VALUES('apple','crisp');
SELECT * FROM @fruits;
假设我想从结果中省略所有带有attribute='pit'
的记录,如果还有另一个与attribute='seeds'
相同类型的水果。
如何使用SQL Server 2016编写该查询?
解决方法
您可以使用note exists
和一些布尔逻辑:
select f.*
from @fruits f
where
attribute <> 'pit'
or not exists (
select 1
from @fruits f1
where f1.type = f.type and f1.attribute = 'seeds'
)
当给定类型也具有属性“种子”时,这将过滤出属性“坑”的记录。
如果条件表示为否定,则遵循起来可能会更简单:
select f.*
from @fruits f
where not (
attribute = 'pit'
and exists (
select 1
from @fruits f1
where f1.type = f.type and f1.attribute = 'seeds'
)
替代方法使用窗口函数:
select *
from (
select
f.*,max(case when attribute = 'seeds' then 1 else 0 end) over(partition by type) has_seeds
from @fruits f
) f
where not (attribute = 'pit' and has_seeds = 1)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。