如何根据相应的列值获取记录

时间:2016-12-21 19:48:11

标签: sql oracle

我下面有一个表A,其中包含“a_id”和“b_id”列。我需要得到所有a_id的两个(100,200)作为b_id值

A
a_id  b_id
---- ------
1      100
1      200
2      100
3      100
4      100
4      200
5      100
5      300

我需要获得如下所示的输出

a_id  b_id
---- ------
1     100
1     200
4     100
4     200

2 个答案:

答案 0 :(得分:0)

您必须使用相同的表格JOIN。像下面的东西

select a.a_id, a.b_id
from A a
join A b on a.a_id = b.a_id
where a.b_id = 100
and b.b_id = 200;

答案 1 :(得分:0)

概念证明。此解决方案返回给定a_id的所有行,只要至少有一行b_id=100,另一行b_id=200为此a_id。如果相同的a_id还有其他行具有b_id的不同值(如果在输入中可以这样做),那么这些行也将被返回。如果有多行b_id=100,则相同 - 将返回所有重复项。

根据实际要求(目前尚不清楚 - 请参阅我对OP的评论),如果只需要a_id值,则可以使用GROUP BY和HAVING更简单的解决方案,而不是原来的行。

with
     table_a ( a_id, b_id ) as (
       select 1, 100 from dual union all
       select 1, 200 from dual union all
       select 2, 100 from dual union all
       select 3, 100 from dual union all
       select 4, 100 from dual union all
       select 4, 200 from dual union all
       select 5, 100 from dual union all
       select 5, 300 from dual
     )
-- end of test data; SQL query begins below this line
select a_id, b_id
from (
       select a_id, b_id, 
              count(case b_id when 100 then 1 end) over (partition by a_id) as ct_1,
              count(case b_id when 200 then 1 end) over (partition by a_id) as ct_2
       from   table_a
     )
where ct_1 > 0 and ct_2 > 0
;

A_ID  B_ID
----  ----
   1   100
   1   200
   4   100
   4   200
相关问题