简体   繁体   中英

sql server join tables without primary key using common columns

I have 2 tables

     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

I don't have a way to join these 2 tables as the Table1_Id is actually the Id of a temp table that loads both these tables.
That table gets wiped out after each load.

I want to show excess units in the first table.

So far my approach has been

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

However I am worried that I may run into a situation where I get 2 Table2 records and I won't know which one corresponds to the Table1

Eg:

While Selecting n3 records, how can I associate the first and second n3 records of Table1 with the first and second n3 records of Table2 ?

use row_number() to generate a sequence no for joining

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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