假设我有两个表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
你怎么解决这个问题?
答案 0 :(得分: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
答案 1 :(得分: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
)