[英]SQL JOIN to get the compare two values/row from table “A” and the same row from table “B”
[英]SQL Query to get two values from a table in same result row
我有一个表,其中包含一个始终以 AB(唯一)开头的标识符和一个键值(非唯一)
ID Key
------------------
AB1234 10001
28376 10001
AB5678 10002
7180 10002
我需要能够查询并获取每个键值的单行结果。 每个键总是只有两个不同的 ID 值,因此我需要以下结果:
ID1 ID2 Key
----------------------------
AB1234 28376 10001
AB5678 7180 10002
我什至不确定这是否可能
每个键总是只有两个不同的 ID 值
在这种情况下,可能会执行类似这样的操作(第 1 - 6 行中的示例数据;查询从第 7 行开始):
SQL> with test (id, key) as
2 (select 'AB1234', 10001 from dual union all
3 select '1234' , 10001 from dual union all
4 select 'CD5678', 10002 from dual union all
5 select '5678' , 10002 from dual
6 )
7 select min(id) id1,
8 max(id) id2,
9 key
10 from test
11 group by key;
ID1 ID2 KEY
------ ------ ----------
5678 CD5678 10002
1234 AB1234 10001
SQL>
它可以通过下面提到的方式完成。 如果可以确认ID2始终和ID1的substring保持一致,position保持不变。 下面提到的是这个的代码
Select id as ID1, substr(id,3,6) as ID2, key
from <table_name> where len(id)=6
group by 3
那就试试这个
with cte as (Select id as id1, key from <table_name> where len(id)=6),
cte2 as (select id as id2, key from <table_name> where len(id)=4)
select cte.id1, cte2.id2, cte.key from cte join cte2 on cte.key=cte2.key
group by 3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.