2016-06-22 135 views
2

我有兩個表如何使用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

什麼是兩個表之間的關係,也就是爲什麼在resul因爲我們有第二個表ID 50和40,在表2中,我們有ID 40,20。 – CiucaS

+0

沒有關係 –

+0

@Ravi Kumar,爲什麼P&Q的ID在tbl_test2和您的預期結果上有所不同? – Ruhaan

回答

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
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