0

假设我有两个表 A 和 B

表 A

name   |   age
----------------
jack   |  13
hanna  |   28

表 B

 id
-----
 1
 2

我想在另一个表 C 中插入以下内容

表 C

id   |  name  |  age
--------------------
1    |  jack  | 13
2    | hanna  | 28

我正在做这个

INSERT INTO C (id, name, age)
SELECT   b.id,  a.name,  a.age
FROM A a, B b

而不是得到我想要的,我得到了这个:

id   |  name  |  age
--------------------
1    |  jack  |  13
1    |  hanna |  28
2    |  jack  |  13
2    |  hanna |  28

你怎么能解决这个问题?

4

2 回答 2

2
declare @a table (name varchar(50),age int)
Declare @b table (id int)

insert into @a 
select 'jack',13
union select 'hanna',28

insert into @b
select 1
union select 2

Select id,name,age from
(
Select a.* ,ROW_Number() over (order by name) as rn
from @a a
)x
JOIN
(
Select b.* ,ROW_Number() over (order by ID) as rn
from @b b
)y
ON x.rn=y.rn
order by ID
于 2013-07-22T11:54:51.583 回答
0

您可以编写此查询以在表 c 中插入所需的行

insert into #c
select id, name, age from (
 ( select ROW_NUMBER() over (order by name) as Aid, name, age from #A ) ATest
inner join (select ROW_NUMBER() over (order by id) as Bid, id from #B) Btest on Aid = Bid
)
于 2013-07-22T12:08:15.453 回答