从具有相同 ID 的 2 个表左连接

Left join from 2 tables with same ID

我有 tabl1e1 和 table2 的数据
表 1

location    costA
 a           5
 a           10
 a           15
 b           11
 b           12

表2

Location    CostB
 a          100
 b          100

我的目标是获得结果

location    costA   costB
  a          5       100
  a          10       
  a          15       
  b          11      50
  b          12       

我的查询

select T1.location, T1.cost
from (
  select location, cost
  , row_number() over ( partition by location order by cost) rownumber
  from table1
) T1 left join (
  select location, cost
  , row_number() over ( partition by location order by cost ) rownumber
  from table2
) T2 on T2.location = T2.cost and T1.rownumber = T2.rownumber

我得到了

location    costA    missing costB column
 a           5
 a           10
 a           15
 b           11
 b           12  

不知道为什么,但你能指出遗漏的那个吗?谢谢。

加入

T2 on T2.location = T2.cost and T1.rownumber = T2.rownumber

应该在

 T2 on T1.location = T2.location and T1.rownumber = T2.rownumber
select 
  T1.location, 
  T1.costA,
  T2.costB
from (
  select 
    location, 
    costA,
    row_number() over ( partition by location order by costA) rownumber
  from table1
) T1 
left join (
  select 
    location, 
    costB, 
    row_number() over ( partition by location order by costB ) rownumber
  from table2
) T2 
on T1.location = T2.location and T1.rownumber = T2.rownumber
GO
location | costA | costB
:------- | ----: | ----:
a        |     5 |   100
a        |    10 |  null
a        |    15 |  null
b        |    11 |   100
b        |    12 |  null

db<>fiddle here

首先,您期望结果中有三个列,而您的 select 语句仅包含 2 个。

select T1.Location, T1.Cost

第二个连接应该是

T2 on T1.[location] = T2.[location] and T1.rownumber = T2.rownumber

下面是完整的工作示例

DECLARE @table1 as table
(
    [location] char,
    costA int
)
DECLARE @table2 as table
(
    [location] char,
    costB int
)

INSERT INTO @table1
VALUES
 ('a', 5)
,('a', 10)
,('a', 15)
,('b', 11)
,('b', 12)
 
INSERT INTO @table2
VALUES
 ('a', 100)
,('b', 100)

select T1.[location], T1.costA, T2.costB
from (
  select [location], costA 
  , row_number() over ( partition by location order by costA) rownumber
  from @table1
) T1 left join (
  select [location], costB
  , row_number() over ( partition by location order by costB ) rownumber
  from @table2
) T2 on T1.[location] = T2.[location] and T1.rownumber = T2.rownumber