一个表有一列是日期,比如02/11/2006
03/11/2006
04/11/2006
15/11/2006另一个表有一列也是日期,比如03/11/2006
16/11/2006怎么写一SQL语句让连个表联合,条件是第一个表最接近且小于第二个表的列,如:
02/11/2006 03/11/2006
03/11/2006 03/11/2006
04/11/2006 16/11/2006
15/11/2006 16/11/2006最后10分了,多谢,等着写好下班回家了。
03/11/2006
04/11/2006
15/11/2006另一个表有一列也是日期,比如03/11/2006
16/11/2006怎么写一SQL语句让连个表联合,条件是第一个表最接近且小于第二个表的列,如:
02/11/2006 03/11/2006
03/11/2006 03/11/2006
04/11/2006 16/11/2006
15/11/2006 16/11/2006最后10分了,多谢,等着写好下班回家了。
解决方案 »
- 问个效率的问题
- 同一服务器,根据一个库的表更新另一库的表
- select语句的一个问题
- 如何在现有的表上设自动增加列
- 如何对这个简单的sql语句进行优化.
- 如何将SQL中的表导入TXT文本文件??谢谢 !!
- 高分请教SQL语句。关于字符串导入到对应表中!
- 我连一台 sql服务器,出现“超时已过期”错误,连不上去,有谁告诉我是什么原因么?
- 怎样设计一个有动态的表的数据库?
- 如何在两个表中找出不同数据
- 某些sql执行后,在消息中,会发现有worktable,I/O很大,解释此现象
- 请邹健、libin_ftsafe(子陌红尘:当libin告别ftsafe)等高手进来看一下这段SQL的写法,能不能再优化一下
declare @t2 table (date datetime)insert into @t1
select convert( datetime,'02/11/2006' ,103 ) union all
select convert( datetime,'03/11/2006' ,103 ) union all
select convert( datetime,'04/11/2006' ,103 ) union all
select convert( datetime,'07/11/2006' ,103 ) union all
select convert( datetime,'15/11/2006' ,103 )insert into @t2
select convert( datetime,'04/11/2006' ,103 ) union all
select convert( datetime,'05/11/2006' ,103 ) union all
select convert( datetime,'16/11/2006' ,103 )select t1.date,(select min(t2.date) from @t2 t2 where t2.date >t1.date )
from @t1 t1 date
------------------------------------------------------ ------------------------------------------------------
2006-11-02 00:00:00.000 2006-11-04 00:00:00.000
2006-11-03 00:00:00.000 2006-11-04 00:00:00.000
2006-11-04 00:00:00.000 2006-11-05 00:00:00.000
2006-11-07 00:00:00.000 2006-11-16 00:00:00.000
2006-11-15 00:00:00.000 2006-11-16 00:00:00.000(所影响的行数为 5 行)
min(datediff(day,'t1.date','t2.date'))
declare @t2 table (date datetime)insert into @t1
select convert( datetime,'02/11/2006' ,103 ) union all
select convert( datetime,'03/11/2006' ,103 ) union all
select convert( datetime,'04/11/2006' ,103 ) union all
select convert( datetime,'07/11/2006' ,103 ) union all
select convert( datetime,'15/11/2006' ,103 )insert into @t2
select convert( datetime,'04/11/2006' ,103 ) union all
select convert( datetime,'05/11/2006' ,103 ) union all
select convert( datetime,'16/11/2006' ,103 )
select t1.date as date1,date2=(select top 1 date from @t2 t2 where t2.date>t1.date order by date asc) from @t1 t1(所影响的行数为 5 行)
(所影响的行数为 3 行)date1 date2
------------------------------------------------------ ------------------------------------------------------
2006-11-02 00:00:00.000 2006-11-04 00:00:00.000
2006-11-03 00:00:00.000 2006-11-04 00:00:00.000
2006-11-04 00:00:00.000 2006-11-05 00:00:00.000
2006-11-07 00:00:00.000 2006-11-16 00:00:00.000
2006-11-15 00:00:00.000 2006-11-16 00:00:00.000(所影响的行数为 5 行)