如何使用SQL Server 2008将两个表数据合并为一个

时间:2016-06-22 05:19:41

标签: sql sql-server sql-server-2008

我有两张桌子

表#1:tbl_test1

id | product1 | price1|
---+----------+-------+
1  | A        | 200   |
2  | B        | 250   |
3  | C        | 300   |

表#2:tbl_test2

id | product2 | price2|
---+----------+-------+
40 | P        | 200   |
20 | Q        | 250   |

我希望得到我给定的格式

id | product1 | price1|id | product2 | price2|
---+----------+-------+---+----------+-------+
1  | A        | 200   |50 | P        | 200   |
2  | B        | 250   |40 | Q        | 250   |
3  | C        | 300   |   |          |       |

请帮忙......

2 个答案:

答案 0 :(得分:5)

我不知道您的最终游戏是什么,但如果您只想并排显示数据,则需要使用FULL JOIN。此外,您必须为每个表添加ROW_NUMBER

WITH CteTest1 AS(
    SELECT *,
        rn = ROW_NUMBER() OVER(ORDER BY id)
    FROM #tbl_test1
),
CteTest2 AS(
    SELECT *,
        rn = ROW_NUMBER() OVER(ORDER BY id)
    FROM #tbl_test2
)
SELECT
    t1.id, t1.product1, t1.price1,
    t2.id, t2.product2, t2.price2
FROM CteTest1 t1
FULL JOIN CteTest2 t2
    ON t2.rn = t1.rn

ONLINE DEMO

答案 1 :(得分:-1)

declare @FirstTable table (StudentId int, SubjectId int)
declare @SecondTable table (MarksId int, RankId int, LastRank int)

insert into @FirstTable values (1, 1)
insert into @FirstTable values (1, 2)
insert into @FirstTable values (1, 3)

insert into @SecondTable values (1, 4, 10)
insert into @SecondTable values (1, 5, 11)

;with XmlTable (RowNumber, StudentId, SubjectId) as
(
    select row_number() over(order by StudentId) as RowNumber, * from @FirstTable
)
,TechnicalIdsTable (RowNumber, MarksId, RankId, LastRank) as
(
    select row_number() over(order by MarksId) as RowNumber, * from @SecondTable
)
select x.StudentId, x.SubjectId, t.MarksId, t.RankId, t.LastRank from XmlTable x 
left join TechnicalIdsTable t
on x.RowNumber = t.RowNumber