3

对于这两个表:

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');
4

3 回答 3

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
于 2012-04-30T07:09:49.747 回答
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)

如果您需要按照您的建议“合并”这两个表,我会尝试添加一些“合并”列来这样做,而不是使用这种方法。

于 2012-04-27T22:31:34.417 回答
0

不.. 没有办法可靠地获得您想要的输出。

看起来您的数据模型缺少一些信息。即某种方式将行从测试 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
于 2012-04-30T02:03:54.467 回答