[英]Select unique field1 that has >1 distinct instances of field2 associated with it?
How can I query for the distinct field1 instances that have multiple distinct corresponding field2 values?如何查询具有多个不同对应 field2 值的不同 field1 实例?
field1![]() |
field2![]() |
---|---|
a![]() |
apple![]() |
b ![]() |
grape![]() |
c ![]() |
banana![]() |
b ![]() |
orange![]() |
a![]() |
apple![]() |
In this example I want to return "b", since there are at least 2 distinct values (grape and orange) for field2 that correspond to it.在此示例中,我想返回“b”,因为 field2 至少有 2 个不同的值(葡萄和橙色)与之对应。 I don't wan't "a" since there is only 1 unique field2 value that corresponds, "apple".
我不想“a”,因为只有 1 个唯一的 field2 值对应,“apple”。
I have tried我努力了
with all_unique_combos as (
select distinct field1, field2
from table
)
select field1
from all_unique_combos
group by field1
having count(field2) > 1
I actually think this is right and would give me what I need.我实际上认为这是正确的,并且会给我我需要的东西。 But at the moment it's returning 0 rows so I kinda need a sanity check.
但目前它返回 0 行,所以我有点需要进行健全性检查。 Thanks for any input either way.
感谢您的任何输入。
You can use aggregation:您可以使用聚合:
select field1
from t
group by field1
having min(field2) <> max(field2);
A straight-forward approach uses group by
and having
:直接的方法使用
group by
和having
:
select field1
from mytable
group by field1
having min(field2) <> max(field2)
Using COUNT(DISTINCT...)
:使用
COUNT(DISTINCT...)
:
select field1
from tab
group by field1
having count(disitnct field2) > 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.