简体   繁体   English

SQL:如何通过元素之一从结果集中排除组,而不使用子查询

[英]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
  1. I need to output 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成员的整个团体应被排除在外
  2. Use of subqueries (or CTE or NOT EXISTS or views or T-SQL inline functions) is not allowed! 不允许使用子查询(或CTE或NOT EXISTS或视图或T-SQL内联函数)!
  3. Use of except is not allowed! 不允许使用except
  4. Use of cursors is not allowed. 不允许使用游标。

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 byhaving

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM