[英]SQL: How to exclude group from result set by one of the elements, not using subqueries
Input: 输入:
id group_id type_id
1 1 aaaaa
2 1 BAD
3 2 bbbbb
4 2 ccccc
5 3 ddddd
6 3 eeeee
7 3 aaaaa
group_id
s which consist only of a members for which type_id <> 'BAD'
. group_id
,它仅由type_id <> 'BAD'
的成员组成。 A whole group with at least one BAD
member should be excluded BAD
成员的整个团体应被排除在外 NOT EXISTS
or views or T-SQL inline functions) is not allowed! NOT EXISTS
或视图或T-SQL内联函数)! except
is not allowed! except
! Any solutions which trick the rules above are appreciated. 任何欺骗上述规则的解决方案都应受到赞赏。 Any RDBMS is ok.
任何RDBMS都可以。
Bad example solution producing correct results, (using except
): 产生正确结果的不良示例解决方案,(使用
except
):
select distinct group_id
from input
except
select group_id
from input
where type_id = 'bad'
group by group_id, type_id
Output: 输出:
group_id
2
3
I would just use group by
and having
: 我只使用
group by
并having
:
select group_id
from input
group by group_id
having min(type_id) = 'good' and max(type_id) = min(type_id);
This particular version assumes that type_id
(as in the question) does not take on NULL
values. 此特定版本假定
type_id
(如问题中所示)不采用NULL
值。 It is easily modified to take that into account. 它很容易修改以考虑到这一点。
EDIT: 编辑:
If you are looking for one bad, then just do: 如果您正在寻找一种不好的方法,请执行以下操作:
select group_id
from input
where type_id = 'bad'
group by group_id;
Group by group_id
and count occurrences of 'BAD'
: 按
group_id
并计数'BAD'
:
select group_id
from mytable
group by group_id
having count(case when type_id = 'BAD' then 'count me' end) = 0;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.