sql - 如果同一组中存在另一条记录,则省略组中的记录
问题描述
如果同一组中有具有特定值的记录,我正在尝试从一组结果中删除记录。我试图将我的复杂问题调整为一个简单的例子:
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)
推荐阅读
- r - 使用 write_xes 函数时出错:默认值 [[datatype]] 中的错误:无效的下标类型“列表”
- sql - 如何在 Google Big Query 的特定范围内查询多个日期
- python - softmax的输出使得二进制交叉熵的输出NAN,怎么办?
- html - 如何突出显示用户输入中无效的单词
- python-3.x - python3 和 pystfp 中的 AWS Secrets Manager 密码问题
- android - 如何使 InetAddress.reachable() 执行得更快?
- python - 如何在网站上抓取嵌入的整数
- docker - Docker:构建映像时永久获取文件
- java - java中的四舍五入问题
- python - 使用 python 和 html 发送邮件