首页 > 解决方案 > 如果同一组中存在另一条记录,则省略组中的记录

问题描述

如果同一组中有具有特定值的记录,我正在尝试从一组结果中删除记录。我试图将我的复杂问题调整为一个简单的例子:

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 编写该查询?

标签: sqlsql-servertsqlsubquery

解决方案


您可以使用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)

推荐阅读