简体   繁体   中英

SQL query for fetching a single column with multiple values

Consider the below table:

Table1

id | status
------------
1  | A
2  | B
3  | C
1  | B
4  | B
5  | C
4  | A

Desired output is 1 and 4 as they are having status as both 'A' and 'B'.

Can we write an query for this? I tried to query it using conditions like 'AND', 'UNION' and 'OR', but it did not return me the desired result.

If you want the ids with more than 1 statuses:

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

You can use aggregation:

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

If the table allows duplicates, then use count(distinct status) = 2 .

Try this one, you can do without using having() as well

select
    id
from
(
    select
        id,
        count(distinct status) as cnt
    from yourTable
    group by
        id
) val
where cnt > 1 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM