[英]How to get the records based on corresponding column values
我在下面的表A中有列“ a_id”和“ b_id”。 我需要獲取所有具有(100,200)作為b_id值的a_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
您將必須使用同一張表進行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;
概念證明 。 此解決方案返回給定a_id
所有行,只要此a_id
至少有一行b_id=100
且另一行b_id=200
。 如果相同的a_id
還具有其他行,且b_id
值不同(如果在輸入中可能這樣),則也將返回這些行。 如果有多行b_id=100
-將返回所有重復項。
根據實際需求(目前尚不清楚,請參閱我對OP的評論),使用GROUP BY和HAVING甚至可以實現更簡單的解決方案-如果僅需要a_id
值,而不需要原始行。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.