Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/oracle/10.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用于获取具有多个值的单个列的SQL查询_Sql_Oracle_Group By_Oracle10g - Fatal编程技术网

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

用于获取具有多个值的单个列的SQL查询,sql,oracle,group-by,oracle10g,Sql,Oracle,Group By,Oracle10g,考虑下表: 表1 id | status ------------ 1 | A 2 | B 3 | C 1 | B 4 | B 5 | C 4 | A 所需输出为1和4,因为它们的状态为“A”和“B” 我们可以为此编写查询吗?我尝试使用“AND”、“UNION”和“OR”等条件查询它,但它没有返回所需的结果。您可以使用聚合: select id from t where status in ('A', 'B') group by id having count(*) = 2;

考虑下表:

表1

id | status
------------
1  | A
2  | B
3  | C
1  | B
4  | B
5  | C
4  | A
所需输出为1和4,因为它们的状态为“A”和“B”


我们可以为此编写查询吗?我尝试使用“AND”、“UNION”和“OR”等条件查询它,但它没有返回所需的结果。

您可以使用聚合:

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

如果该表允许重复,则如果希望ID具有1个以上的状态,请使用
count(distinct status)=2

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

试试这个,您也可以不使用
having()

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

为什么需要外部查询>只是想不使用
have
子句,如果需要显示特定计数范围之间的id。如果有任何缺点,请告诉我。谢谢