请看下表:
表1
所需的输出为1和4,因为它们的状态分别为'A'和'B'。我们可以为此查询吗?我尝试使用“ AND”,“ UNION”和“ OR”之类的条件查询它,但没有返回我想要的结果。
如果您希望ID具有不止一种状态:
select id
from tablename
group by id
having count(distinct status) > 1
您可以使用聚合:
select id
from t
where status in ('A', 'B')
group by id
having count(*) = 2;
如果表允许重复,则使用count(distinct status) = 2
。
尝试此操作,也可以不使用having()
来完成
select
id
from
(
select
id,
count(distinct status) as cnt
from yourTable
group by
id
) val
where cnt > 1