Sql server SQL连接避免笛卡尔积

Sql server SQL连接避免笛卡尔积,sql-server,Sql Server,尝试使用下表避免笛卡尔积 #t1 (1,'2019-03-01','TN',0.33) (2,'2019-03-01','TN',0.13) (3,'2019-03-01','TN',0.63) #t2 ('2019-03-01','TN',3.1) #t2 ('2019-03-01','TN',4.1) #t2 ('2019-03-01','TN',5.1) select * from #t1 select * from #t2 select a.cd,a.loc,(a.

尝试使用下表避免笛卡尔积

#t1 (1,'2019-03-01','TN',0.33)
    (2,'2019-03-01','TN',0.13)
    (3,'2019-03-01','TN',0.63)

#t2 ('2019-03-01','TN',3.1)
#t2 ('2019-03-01','TN',4.1)
#t2 ('2019-03-01','TN',5.1)

select * from #t1
select * from #t2

select a.cd,a.loc,(a.sales*b.multi)
from #t2 a join #t1 b on a.cd=b.cd and a.loc=b.loc
这可以理解地返回笛卡尔乘积:

2019-03-01  TN  1.023
2019-03-01  TN  1.353
2019-03-01  TN  1.683
2019-03-01  TN  0.403
2019-03-01  TN  0.533
2019-03-01  TN  0.663
2019-03-01  TN  1.953
2019-03-01  TN  2.583
2019-03-01  TN  3.213
如何编写查询以返回以表B为驱动程序的单行结果集

预期产出:

1  2019-03-01 TN (0.33*3.1) -- value of
2  2019-03-01 TN (0.13*4.1) 
3  2019-03-01 TN (0.63*5.1) 

看起来这些记录实际上与它们在表中的存在顺序有关。在表B中添加一个标识列并加入其中。源数据上的列名会有帮助吗?#t2中是否有一个值对应于#t1中的第一列(例如1、2、3)?您如何知道要将#t1中第一行的销售值与#t2中第一行的多值相乘?表行没有固有的顺序,如果t2中有四行与t1中的三行相匹配,您希望发生什么?
declare @t1 table(id int, cd date, loc varchar(2), sales money);
insert into @t1(id, cd,loc, sales)
values
--#t1 
(1,'2019-03-01','TN',0.33),
(2,'2019-03-01','TN',0.13),
(3,'2019-03-01','TN',0.63);


declare @t2 table(cd date, loc varchar(2), multi decimal(5, 2));
insert into @t2(cd, loc, multi) 
values
('2019-03-01','TN',3.1),
('2019-03-01','TN',4.1),
('2019-03-01','TN',5.1)

select *
from 
(
    --this is better...than using t1 directly, especially if other locs are there (they wont have id starting from 1, 2, 3)
    select *, row_number() over(partition by cd, loc order by id) as rownum
    from @t1 
) as t1
join
(
    select *, row_number() over(partition by cd, loc order by multi) as rownum --lowest multi gets 1, next gets 2 and so on
    from @t2
) as t2 on t1.cd = t2.cd and t1.loc = t2.loc and t1.rownum = t2.rownum;