繁体   English   中英

不使用主列的主键的SQL Server连接表

[英]sql server join tables without primary key using common columns

我有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个Table2记录,而我不知道哪一个对应于Table1

例如:

虽然选择n3的记录,我怎么能在联想first and second n3的记录Table1first and second n3的记录Table2

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM