SQL 处理多个 AND 条件

Rob*_*Rob 3 oracle relational-division

我有以下数据:

机构_编号 信用类型
1 1
1 2
2 1

我有一个列表框,以便用户可以选择多个 Cred_type,他们希望能够选择 OR 或 AND 条件。

对于 OR 我有这样的 AND CRED_TYPE IN (1,2)

对于AND,我真是摸不着头脑。他们的意思是,他们想要一份具有cred type 1和cred_type 2的机构列表。也许我没有想清楚,但这是逐行的,所以这样做会导致没有结果。

AND cred_type = 1 AND cred_type = 2 -- 您不能让一行有两个不同的值,这将不会返回任何结果。

它们要求用户可以选择 10、20 或更多,因此为每个代码编写一堆代码并将它们组合起来非常困难 - 但这是我迄今为止唯一的想法。会是这样的

Select institution_no from table where cred_type = 1
UNION 
Select institution_no from table where cred_type = 2
Run Code Online (Sandbox Code Playgroud)

-- 这会将两者结合起来并得到我想要的东西,但你可以想象其中 10 或 20 个的所有代码。

Erg*_*sha 6

您可以使用HAVING子句。

例如:如果您有一个信用类型为 1、2、3、4、5、6 的机构列表,您可以尝试以下操作:

select institution_no 
from table 
where cred_type in (1,2,3,4,5,6)
group by institution_no
having count(distinct cred_type)=6;
Run Code Online (Sandbox Code Playgroud)

编辑:使用的查询OP

with cte as ( 
             select distinct institution_no, 
                    CERT_TYPE 
             from credentialing 
             where CERT_TYPE in (1,2)
             ) 
select institution_no, 
       count(institution_no) 
from cte 
group by institution_no 
having count(institution_no) = 2;
Run Code Online (Sandbox Code Playgroud)