WHERE子句中的SQL Filter Resultset

时间:2016-06-09 07:44:09

标签: sql firebird

我遇到了Resultset-Filter的问题。

我的SQL查询提供了一个如下所示的列表:

LOAD_NR -------- REASON_ID
399              19
399              20  
399              21
399              22  
400              19
400              20
401              20
402              20

现在我想要一个包含例如加载号的列表。 Reason_ID = 19 AND Reason_ID = 20。 在这个例子中,这将是:399和400。

我正在使用Firebird数据库。

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT LOAD_NR
FROM mytable
WHERE REASON_ID IN (19, 20)
GROUP BY LOAD_NR
HAVING COUNT(DISTINCT REASON_ID) = 2

答案 1 :(得分:0)

您需要选择满足这两个条件的所有值,因此您需要单独检查存在:

select distinct load_nr
from thetable a
where exists (select 1 from thetable where load_nr = a.load_nr and reason_id = 19)
and exists (select 1 from thetable where load_nr = a.load_nr and reason_id = 20)

或者你可以使用ANY (or SOME),但这可能会有更差的表现:

select distinct load_nr
from thetable a
where 19 = any (select reason_id from thetable where load_nr = a.load_nr)
and 20 = any (select reason_id from thetable where load_nr = a.load_nr)