如何逐个映射2个不同的记录集?

时间:2013-01-08 13:50:04

标签: sql sql-server

让我说我有2个SQL查询。表A包含,

ID
--
1
1
1
2
3
4

此查询,

Select distinct ID1 FROM A

给了我,

ID
--
1
2
3
4

第二个

Select ID2 FROM B

给了我,

ID2
--
8
21
33
43

2如何获得此记录集?

ID1  ID2
---  ---
 1    8
 2    21
 3    33
 4    43

1 个答案:

答案 0 :(得分:5)

您没有指定sql server的版本,但如果您使用的是sql server 2008+,则可以通过向每个表添加row_number()然后加入row_number()来实现此目的。 }:

select a.id, b.id2
from
(
  select id, row_number() over(order by id) rn
  from a
) a
inner join
(
  select id2, row_number() over(order by id2) rn
  from b
) b
  on a.rn = b.rn

请参阅SQL Fiddle with Demo

如果您只想使用DISTINCT值,那么您应该可以使用:

select a.id, b.id2
from
(
  select id, row_number() over(order by id) rn
  from
  (
    select distinct id
    from a
  ) a
) a
inner join
(
  select id2, row_number() over(order by id2) rn
  from b
) b
  on a.rn = b.rn;

请参阅SQL Fiddle with Demo

如果每个表中的行数不同,那么您可能希望使用FULL OUTER JOIN

select a.id, b.id2
from
(
  select id, row_number() over(order by id) rn
  from
  (
    select distinct id
    from a
  ) a
) a
full outer join
(
  select id2, row_number() over(order by id2) rn
  from b
) b
  on a.rn = b.rn;

请参阅SQL Fiddle with Demo