对于这两个表:
CREATE TABLE TEST1 ( ID INTEGER ,key VARCHAR(50),VALUE1 VARCHAR(50));
CREATE TABLE TEST2 ( ID INTEGER ,key VARCHAR(50),VALUE2 VARCHAR(50));
表1:
130, 'HANSEN', 'STREET1'
130, 'HANSEN', 'STREET2'
130, 'HANSEN', 'STREET3'
120, 'HANSEN', 'STREET5'
120, 'HANSEN', 'STREET6'
表2:
130, 'HANSEN', 'ZIP1'
130, 'HANSEN', 'ZIP2'
130, 'HANSEN', 'ZIP3'
120, 'HANSEN', 'ZIP4'
120, 'HANSEN', 'ZIP5'
是否可以将输出作为:
130, 'HANSEN', 'ZIP1','STREET1'
130, 'HANSEN', 'ZIP2','STREET2'
130, 'HANSEN', 'ZIP3','STREET3'
120, 'HANSEN', 'ZIP4','STREET5'
120, 'HANSEN', 'ZIP5','STREET6'
尝试使用id,key的内部联接,但我得到了笛卡尔积
感谢您的帮助。
帮助程序脚本(如果有人愿意测试它):
DROP TABLE TEST1;
DROP TABLE TEST2;
CREATE TABLE TEST1 ( ID INTEGER ,key VARCHAR(50),VALUE1 VARCHAR(50));
CREATE TABLE TEST2 ( ID INTEGER ,key VARCHAR(50),VALUE2 VARCHAR(50));
INSERT INTO TEST1 VALUES (130, 'HANSEN', 'STREET1');
INSERT INTO TEST1 VALUES (130, 'HANSEN', 'STREET2');
INSERT INTO TEST1 VALUES (130, 'HANSEN', 'STREET3');
INSERT INTO TEST1 VALUES (120, 'HANSEN', 'STREET5');
INSERT INTO TEST1 VALUES (120, 'HANSEN', 'STREET6');
INSERT INTO TEST2 VALUES (130, 'HANSEN', 'ZIP1');
INSERT INTO TEST2 VALUES (130, 'HANSEN', 'ZIP2');
INSERT INTO TEST2 VALUES (130, 'HANSEN', 'ZIP3');
INSERT INTO TEST2 VALUES (120, 'HANSEN', 'ZIP4');
INSERT INTO TEST2 VALUES (120, 'HANSEN', 'ZIP5');
答案 0 :(得分:1)
它不漂亮,根据Oracle为您提供结果集的顺序,您可能会得到奇怪的结果,但您可以尝试:
select t1.id, t1.key, t1.value1, t2.value2
from
(select rownum rn, id, key, value1 from test1) t1
inner join
(select rownum rn, id, key, value2 from test2) t2
using (rn)
如果您需要按照建议“合并”这两个表,我会尝试添加一些“合并”列来执行此操作而不使用此方法。
答案 1 :(得分:1)
这应该这样做:
with t1 as (
select id,
key,
value1,
row_number() over (partition by id order by key, value1) as rn
from test1
),
t2 as (
select id,
key,
value2,
row_number() over (partition by id order by key, value2) as rn
from test2
)
select t1.id,
t2.key,
t2.value2||','||t1.value1
from t1
join t2 on t1.id = t2.id and t1.key = t2.key and t1.rn = t2.rn
order by 1 desc, 3 asc
答案 2 :(得分:0)
不..没有办法可靠地获得你想要的输出。
看起来你的datamodel缺少一些信息。即某种方式将测试1中的行链接到测试2 ..你目前的id / key不够独特。
我认为你能做的最好的事情就是
select *
from test1
inner join test2 using (id,key)
order by 1 desc,2,3,4
给出
的输出130 HANSEN STREET1 ZIP1
130 HANSEN STREET1 ZIP2
130 HANSEN STREET1 ZIP3
130 HANSEN STREET2 ZIP1
130 HANSEN STREET2 ZIP2
130 HANSEN STREET2 ZIP3
130 HANSEN STREET3 ZIP1
130 HANSEN STREET3 ZIP2
130 HANSEN STREET3 ZIP3
120 HANSEN STREET5 ZIP4
120 HANSEN STREET5 ZIP5
120 HANSEN STREET6 ZIP4
120 HANSEN STREET6 ZIP5