我该如何加入这两张桌子?

时间:2016-08-20 05:55:20

标签: sql-server

这是我拥有的两张桌子。

 | StockId | Item1 | Quantity1|
     1        10        5
     1        11        6

 | StockId | Item2 | Quantity2 |
     1        12        4

我需要加入这两个表,以便获得输出:

 | StockId | Item1 | Quantity1 | Item2 | Quantity2 |
      1       10        5          12       4
      1       11        6          -        -

每个表可能包含1行或更多行。我尝试过加入表格,但那不行。

SELECT * FROM Table1 
INNER JOIN Table2 ON Table1.StockId = Table2.StockId

这会给我输出:

 | StockId | Item1 | Quantity1 | Item2 | Quantity2 |
      1       10        5          12       4
      1       11        6          12       4

2 个答案:

答案 0 :(得分:2)

@JamesZ您的查询将在以下场景中失败..您正在基于Item1和Item2生成RN,并且在加入两个您不考虑StockIds的表时也不考虑StockId。 在下面的示例中,我添加了更多行,以确保查询提供正确的结果。

CREATE TABLE #T1 (StockId INT ,Item1 INT,Quantity1 INT)
CREATE TABLE #T2 (StockId INT ,Item2 INT,Quantity2 INT)

INSERT INTO #T1
SELECT 1,10,5 UNION ALL
SELECT 1,11,6 UNION ALL
SELECT 1,9 ,6 UNION ALL
SELECT 1,8 ,6 UNION ALL
SELECT 2,10,5 UNION ALL
SELECT 2,11,6

INSERT INTO #T2
SELECT 1,12,4 UNION ALL 
SELECT 2,12,4

;WITH T1
AS
(
    SELECT ROW_NUMBER() OVER (PARTITION BY StockId ORDER BY Item1) AS RN, * 
    FROM #T1
) 
,T2
AS
(
    SELECT ROW_NUMBER() OVER (PARTITION BY StockId ORDER BY Item2) AS RN, * 
    FROM #T2
)
SELECT T1.StockId,T1.Item1,T1.Quantity1,T2.StockId,T2.Item2,T2.Quantity2
FROM T1 
FULL JOIN T2 ON T1.StockId = T2.StockId AND T1.RN = T2.RN

答案 1 :(得分:1)

您的数据库看起来需要重新思考,因为您的要求不是很清楚,但您可以使用以下内容执行此操作:

select * 
from 
(select row_number() over (order by Item1) as RN, * from Table1) T1
full outer join
(select row_number() over (order by Item2) as RN, * from Table2) T2
on T1.RN = T2.RN