[英]SQL: How to exclude group from result set by one of the elements, not using subqueries
輸入:
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
,它僅由type_id <> 'BAD'
的成員組成。 具有至少一名BAD
成員的整個團體應被排除在外 NOT EXISTS
或視圖或T-SQL內聯函數)! except
! 任何欺騙上述規則的解決方案都應受到贊賞。 任何RDBMS都可以。
產生正確結果的不良示例解決方案,(使用except
):
select distinct group_id
from input
except
select group_id
from input
where type_id = 'bad'
group by group_id, type_id
輸出:
group_id
2
3
我只使用group by
並having
:
select group_id
from input
group by group_id
having min(type_id) = 'good' and max(type_id) = min(type_id);
此特定版本假定type_id
(如問題中所示)不采用NULL
值。 它很容易修改以考慮到這一點。
編輯:
如果您正在尋找一種不好的方法,請執行以下操作:
select group_id
from input
where type_id = 'bad'
group by group_id;
按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.