有两个表,字段值分别如下:
table1_field table2_field
1.1 1
2.2 2.5
1.5 3.2
2.6 4.3
... 5.7
6.5
...
要求两个表连接,上面的例子连接结果是这样的:
1.1——1(大于1而小于2.5)
2.2——1(大于1而小于2.5)
1.5——1(大于1而小于2.5)
2.6——2.5(大于2.5而小于3.2)
就是说连接条件是跟这两个字段的字段值顺序和大小相关,
1.1在1和2.5之间,连接到1
2.2在1和2.5之间,连接到1
1.5在1和2.5之间,连接到1
2.6在2.5和3.2之间,连接到2.5
类推....
怎么写SQL语句?
---------------------------------------------------------------
Select Table1_field,
(select max(table2_field) from table2 where table2_field <= table1_field )
from table1
---------------------------------------------------------------
create table #t1(a char(3))
insert #t1 select '1.1'
insert #t1 select '2.2'
insert #t1 select '1.5'
insert #t1 select '2.6'
create table #t2(a char(3))
insert #t2 select '1'
insert #t2 select '2.5'
insert #t2 select '3.2'
select A.a, max(B.a) b from #t1 A left join #t2 B on A.a > B.a group by A.a
a b
---- ----
1.1 1
1.5 1
2.2 1
2.6 2.5