sql server使用公共列连接没有主键的表

时间:2018-05-10 03:25:35

标签: sql sql-server inner-join distinct primary-key

我有2张桌子

     Id   Name   Units sold
     1    n1,       100 
     2    n2,       95 
     3    n3,       84 
     4    n3,       84 
     5    n5,       100 



  Name   Units sold  Excess Units  Table1_Id
     n1,       100      51            9
     n2,       95       43            10
     n3,       84       100           11
     n3,       84       33            12
     n5,       100      10            13

我没有办法加入这两个表,因为Table1_Id实际上是加载这两个表的临时表的Id
每次加载后该表都会被删除。

我想在第一张表中显示多余的单位。

到目前为止,我的方法一直是

select table1.*, table2.Excess_units from Table1 inner join
Table2 on Table1.Name = Table2.Name and Table1.Units_sold = Table2.Units_Sold

然而,我担心我可能遇到的情况 2表2记录,我不知道哪一个对应于Table1

例如:

在选择n3条记录时,如何将first and second n3的{​​{1}}条记录与Table1的{​​{1}}条记录相关联?

1 个答案:

答案 0 :(得分:1)

使用row_number()生成序列号以便加入

select *
from
(
    select *, rn = row_number() over(partition by name, units_sold order by name)
    from   Table1
) t1
inner join
(
    select *, rn = row_number() over(partition by name, units_sold order by name)
    from   Table2
) t2
on  t1.name = t2.name and t1.units_sold = t2.units_sold and t1.rn = t2.rn