简体   繁体   English

ORACLE,我如何在同一张表中使用两个不同的过滤器?

[英]ORACLE, how i use two diferent filtres in same table?

I have this problem: in the same table i need to get the ID´s with have only two CODES at the same time, EX: 我有这个问题:在同一张表中,我需要同时拥有只有两个CODES的ID,例如:

TABLE1 表格1

ID | CODE
1  | A
1  | B
2  | C
2  | B
3  | C
3  | A
4  | A
5  | C

Example: i need to get only the ID´s with the CODE 'A' and 'B' at same time, in the TABLE1 the answer is only the ID 1 示例:我只需要同时获得带有代码“ A”和“ B”的ID,在表1中答案仅是ID 1

so i count whats ID have two CODE´s: 所以我算什么ID有两个CODE:

SELECT ID
FROM TABLE1
GROUP BY ID
HAVING COUNT(CODE) = 2

And i filter whats CODE´s are 'A' OR 'B' 我过滤什么是“ A”或“ B”

SELECT ID
FROM TABLE1
WHERE (CODE = 'A' OR 'B')

But how i combine this two queries? 但是我如何结合这两个查询?

A slight variation on the answer given by @Lukasz: @Lukasz给出的答案略有不同:

SELECT ID
FROM TABLE1
WHERE Code IN ('A', 'B')
GROUP BY ID
HAVING COUNT(DISTINCT Code) = 2;

Your question is a little ambiguous. 您的问题有点模棱两可。 If you want A/B together -- and other codes are allowed as well -- then: 如果您希望同时使用A / B(也允许使用其他代码),则:

SELECT ID
FROM TABLE1
WHERE CODE IN ('A', 'B')
GROUP BY ID
HAVING MIN(CODE) = 'A' and MAX(CODE) = 'B';

You can also use: 您还可以使用:

HAVING COUNT(DISTINCT CODE) = 2;

However, COUNT(DISTINCT) typically has worse performance. 但是, COUNT(DISTINCT)通常具有较差的性能。

You could use conditional aggregation: 您可以使用条件聚合:

SELECT ID
FROM TABLE1
GROUP BY ID 
HAVING COUNT(DISTINCT CASE WHEN Code IN('A','B') THEN Code END) = 2;

DBFiddle Demo DBFiddle演示

You can do : 你可以做 :

select t1.*
from table1 t1
where not exists (select 1 from table1 t2 where t2.id = t1.id and t2.code = 'C');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何禁止在 Oracle 的表上同时在两个字段中输入相同的值? - How can I disable entering the same values in two fields at the same time on a table in Oracle? 我想对sql oracle不同行进行分组 - I want to group in sql oracle diferent rows Oracle:如何加入两个结果集查询(基于同一张表)然后减去结果? - Oracle: How do I join two result set queries (based on the same table) and then subtract the results? 如何区分表中使用相同查找表的两列? - How can i distinguish between two columns in a table that use the same lookup table? Oracle-在同一表的两列中检查重复项 - Oracle - Check duplicates in two columns in same table 如何检查表是否包含不同的值? - How to check If table contains diferent values? 如果我在表中有两列,如何在oracle中互换列名? - If i have two columns in table how to interchange columns names in oracle? 如何在两个表中同一列的两个AND条件下用Oracle SQL编写SQL语句? - How to write a SQL Statement in Oracle SQL with two AND conditions applying on same column within same table? 如何在oracle 9i中导出不包含一两列的表? - how to export table in oracle 9i that excludes a column or two? 如何使用 select 计数(不同的 x)来计算同一个表中的两个值并在我的 output 中获取两个不同的值? - How can I use select count (distinct x) in order to count two values in the same table and get the the two distinct values in my output?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM