我目前有2个表格,其中包含有关某个项目的信息。第一个表显示给定项目no的各种名称:
Item No Name
1 Name1
1 Name2
1 Name3
第二个表显示给定项目no的各个位置:
Item No Location
1 Location1
1 Location2
我目前正在使用以下语句加入这两个表
Select *
from FirstTable a
Left Join
(
Select *
from SecondTable
) b
on a.itemno = b.itemno
我最终得到了这些数据:
Item No Name Location
1 Name1 Location1
1 Name1 Location2
1 Name2 Location1
1 Name2 Location2
1 Name3 Location1
1 Name3 Location2
我想最终得到的是:
Item No Name Location
1 Name1 Location1
1 Name2 Location2
1 Name3 NULL
如何实现我正在寻找的结果?
答案 0 :(得分:1)
如何使用这样的东西。这会将通用row_number()
分配给表中的每个值,然后您加入该行号值:
select i.[item no],
i.name,
l.location
from
(
select [item no], name,
row_number() over(partition by [item no] order by name) rn
from item
) i
full outer join
(
select [item no], location,
row_number() over(partition by [item no] order by location) rn
from locations
) l
on i.rn = l.rn
您的样本数据的结果是:
| ITEM NO | NAME | LOCATION |
-------------------------------
| 1 | Name1 | Location1 |
| 1 | Name2 | Location2 |
| 1 | Name3 | (null) |