用于获取具有多个值的单列的SQL查询

问题描述 投票:0回答:3

请看下表:

表1

id |状态

1 | A

2 | B

3 | C

1 | B

4 | B

5 | C

4 | A

所需的输出为1和4,因为它们的状态分别为'A'和'B'。我们可以为此查询吗?我尝试使用“ AND”,“ UNION”和“ OR”之类的条件查询它,但没有返回我想要的结果。

sql group-by oracle10g
3个回答
1
投票

如果您希望ID具有不止一种状态:

select id
from tablename
group by id
having count(distinct status) > 1

0
投票

您可以使用聚合:

select id
from t
where status in ('A', 'B')
group by id
having count(*) = 2;

如果表允许重复,则使用count(distinct status) = 2


0
投票

尝试此操作,也可以不使用having()来完成

select
    id
from
(
    select
        id,
        count(distinct status) as cnt
    from yourTable
    group by
        id
) val
where cnt > 1 
© www.soinside.com 2019 - 2024. All rights reserved.