获取一列具有不同值的两行的 ID

kee*_*alm 2 postgresql postgresql-9.4

基本上,我有一个数据集,它是附加到 ID 的内部位置标识符列表(因此每个“一组”地理点都有自己的 ID)。因此,表中存在“id”列和“location”列。

我需要一种方法来查找包含两个不同位置的 ID,即:

身份证 | 地点
--------------
1 | 一种
1 | 乙
1 | C
2 | 一种
2 | C
2 | d

如果我寻找 'a' 和 'd',我会得到 2。
如果我寻找 'a' 和 'b',我会得到 1。
如果我寻找 'a' 和 'c',我会得到12。

我正在使用 PostgreSQL 9.4。

a_h*_*ame 6

select id
from the_table
where location in ('a', 'd')
group by id
having count(distinct location) = 2;
Run Code Online (Sandbox Code Playgroud)