0

嗨,我有两张桌子 A 和 B

表 A:

Order        Pick up
100          Toronto
100          Mississauga
100          Scarborough

表 B

Order              Drop off
100                Oakvile
100                Hamilton
100                Milton

请让我知道如何获得此输出(即我只想加入 A 右侧 B 中的字段)

Order    pickup        Dropoff
100      Toronto       oakvile
100      Mississauga   Hamilton
100      Scarborough   Milton

如何为我尝试加入a.rownum = b.rownum但没有运气的相同内容编写查询。

4

3 回答 3

1

从使用rownum中,我假设您使用的是 Oracle。您可以尝试以下操作:

select a.Order as "order", a.Pickup, b.DropOff
from (select a.*, rownum as seqnum
      from a
     ) a join
     (select b.*, rownum as seqnum
      from b
     ) b
     on a.order = b.order and a.seqnum = b.seqnum;

(这假设所有订单都完全匹配。)

我必须强调,尽管这似乎可行(并且它应该适用于小例子),但它通常不会起作用。而且,它不适用于已删除记录的数据。而且,它可能不适用于并行系统。如果您有少量数据,我建议将其转储到 Excel 中并在那里进行工作——这样,您可以查看这些数据对是否有意义。

此外,如果您确实有一个指定排序的列,那么基本上相同的结构将起作用:

select coalesce(a.Order, b.Order) as "order", a.Pickup, b.DropOff
from (select a.*,
             row_number() over (partition by "order" order by <ordering field>) as seqnum
      from a
     ) a join
     (select b.*,
             row_number() over (partition by "order" order by <ordering field>) as seqnum
      from b
     ) b
     on a.order = b.order and a.seqnum = b.seqnum;
于 2013-06-08T17:54:37.093 回答
1

由于OP没有提到任何RDBMS

我冒昧地将SQL SERVER 2008其作为他的RDBMS。如果 OP 想要以下查询可以轻松转换为任何其他RDBMS

select A.[Order],
    ROW_NUMBER() OVER(ORDER BY A.[Pick up]) rn1,
    A.[Pick up]
    into A1
FROM A
;
select B.[Order],
    ROW_NUMBER() OVER(ORDER BY B.[Drop off]) rn2,
    B.[Drop off]
    into B1
FROM B
;
Select A1.[Order],
    A1.[Pick up],
    B1.[Drop off]
FROM A1
INNER JOIN B1 on A1.rn1=B1.rn2

要测试的 SQL FIDDLE

于 2013-06-08T16:47:45.553 回答
0

我会使用 CTE 和 ROW_NUMBER 窗口函数。

WITH keyed_A AS (
  SELECT
    ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS id
   ,[Order]
   ,[Pick Up]
  FROM A
), keyed_B AS (
  SELECT
    ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) AS id
   ,[Order]
   ,[Drop Off]
  FROM B
)
SELECT
   a.[Pick Up]
  ,b.[Drop Off]
  FROM keyed_A AS a
  INNER JOIN keyed_B AS b
    ON a.id = b.id
;

CTE可以被认为是一个虚拟表,其id 跨越两个表。带有窗口函数ROW_NUMBER的 OVER 子句可用于在 CTE 中创建一个 id。由于我们依赖于记录的物理存储(不是一个好主意,请向表中添加键),我们可以 ORDER BY (SELECT NULL),这意味着只需使用 order in 将被读入。

SQLFiddle 进行测试

于 2013-06-08T17:01:59.417 回答