当所有子级都满足该条件时,根据特定状态检索父级记录

问题描述 投票:-3回答:1

我有表A,B,C。

表A是父级,表B是具有A(1至*多关系)B的子级。表C包含关系链接,表示有多少表B记录到表A的链接。

仅当其所有链接的子级都包含状态传递时,我才需要获取父键,否则需要忽略该记录。

例如:

<< img src =“ https://image.soinside.com/eyJ1cmwiOiAiaHR0cHM6Ly9pLnN0YWNrLmltZ3VyLmNvbS9rNG1URS5qcGcifQ==” alt =“在此处输入图像描述”>

预期结果:父pkey:仅1个。

请帮助我进行SQL查询。!

sql sql-server tsql group-by having-clause
1个回答
0
投票

您想要所有子代状态均为'Pass'的父键。您可以使用聚合,并过滤àhaving子句-就您而言,只能从tableB中获取信息。

select pkey
from tableb 
group by pkey
having min(status) = max(status) and min(status) = 'Pass'

如果“通过”和“失败”是唯一可能的值,则也可以将其表达为:

having min(status) = 'Pass'

如果父表中有更多列,并且您想显示它们,那么一种选择是将上述查询与父表连接起来:

select a.*
from tablea a
inner join (
    select pkey
    from tableb 
    group by pkey
    having min(status) = max(status) and min(status) = 'Pass'
) b on b.pkey = a.pkey

或者您可以使用exists

select a.*
from tablea a
where 
    exists(select 1 from tableb b where b.pkey = a.pkey  and b.status = 'Pass')
    and not exist (select 1 from tableb b where b.pkey = a.pkey  and b.status <> 'Pass')
© www.soinside.com 2019 - 2024. All rights reserved.