加入一个只有1个匹配记录的表

时间:2017-12-04 15:05:16

标签: sql

Mon Dec  4 19:36:23 2017, 98
Tues Dec  5 19:36:28 2017, 99
Wed Dec  6 19:36:21 2017, 95
Thur Dec  7 19:36:23 2017, 89
Fri Dec  8 19:36:20 2017, 93
Sun Dec  10 19:36:23 2017, 98
Mon Dec  11 19:36:25 2017, 97

目前我正在使用以下查询。

--------------------Table1-------------
Table1Id            item      SaleId       Dimensions
1                   test1      41           10*11*12
2                   test2      41           13*14*15

--------------------Table2-------------
Table2Id     item         Description   
1           test1         Test element1 desc 1
2           test1         Test element1 desc 2
3           test2         Test element2 desc 1
4           Test2         Test element2 desc 2

但我想要那样的结果(需要将Table1.item与表2中的项目的第一条记录连接起来)

select Table1.Table1Id, Table1.item, Table1.Dimensions, Table2.Description
on Table1.item = Table2.item
where Table1.SaleId = 41

1 个答案:

答案 0 :(得分:2)

处理此问题的最典型方法是使用ANSI标准row_number()

Select t1.Table1Id, t1.item, t1.Dimensions, t2.Description
from table1 t1 join
     (select t2.*, row_number() over (partition by t2.item order by t2.table2id desc) as seqnum
      from table2 t2
     ) t
     on t1.item = t2.item and t2.seqnum = 1
where t1.SaleId = 41;