postgreSQL选择按多个值分组的项



我有一个类似的表

<表类> 实例值类型tbody><<tr>ins_131日"A"ins_181"B"ins_272"A"ins_39"B"ins_39"C"

这里的典型方法是聚合每个实例的行,并在HAVING子句中使用条件聚合来仅获取符合条件的那些实例:

select instance
from mytable
group by instance
having count(*) filter (where type = 'A') > 0
and count(*) filter (where type = 'B') > 0
order by instance;

我自己没有想到的是isolation在请求评论中的建议:使用INTERSECT,这会导致这个非常简单的查询:

select instance from mytable where type = 'A'
intersect
select instance from mytable where type = 'B'
order by instance;

这两种方法我都喜欢。不过,我的第一种方法更加通用,因为您可以轻松地在该查询中设置各种条件,而无需对其进行太多更改。例如,如果您想将其限制为具有类型A和B而没有其他类型的那些实例。您只需添加一个条件,即类型计数必须为2,或者除a和B以外的类型计数必须为零。

你可以用多种方式做到这一点,但我认为最快的应该是使用exist子句-

SELECT instance
FROM YOUR_TABLE T1
WHERE type = '"A"'
AND EXISTS (SELECT NULL
FROM YOUR_TABLE T2
WHERE T1.instance = T2.instance
AND T2.type = '"B"')

最新更新