簡體   English   中英

SQL:如何通過元素之一從結果集中排除組,而不使用子查詢

[英]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
  1. 我需要輸出group_id ,它僅由type_id <> 'BAD'的成員組成。 具有至少一名BAD成員的整個團體應被排除在外
  2. 不允許使用子查詢(或CTE或NOT EXISTS或視圖或T-SQL內聯函數)!
  3. 不允許使用except
  4. 不允許使用游標。

任何欺騙上述規則的解決方案都應受到贊賞。 任何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 byhaving

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM