求一sql语句

inrie 2005-04-12 05:26:22
有一个表table1,包含两个字段,如下

id date1
1 2004-02-02
2 2004-02-15
3 2004-02-18
4 2004-02-03
5 2004-03-05
6 2004-03-11
7 2004-04-09
... ........

怎样才能找出date1字段中相邻的两个记录间时间间隔最长的那两个记录.(date1字段存日期).谢谢!
...全文
83 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
子陌红尘 2005-04-12
  • 打赏
  • 举报
回复
create table1(id int,date1 datetime)
insert into table1 select 1,'2004-02-02'
insert into table1 select 2,'2004-02-15'
insert into table1 select 3,'2004-02-18'
insert into table1 select 4,'2004-02-03'
insert into table1 select 5,'2004-03-05'
insert into table1 select 6,'2004-03-11'
insert into table1 select 7,'2004-04-09'



select
a.*
from
table1 a,
table1 b
where
abs(a.id-b.id) = 1
and
abs(datediff(day,a.date1,b.date1)) =
(select
max(datediff(day,a.date1,b.date1))
from
table1 a,
table1 b
where
a.id = b.id - 1)
wyb0026 2005-04-12
  • 打赏
  • 举报
回复
楼上写比我快佩服
LBYYBL 2005-04-12
  • 打赏
  • 举报
回复
--测试数据
create table table1(id int identity(1,1),date1 datetime)
insert into table1(date1) select '2004-02-02'
insert into table1(date1) select '2004-02-15'
insert into table1(date1) select '2004-02-18'
insert into table1(date1) select '2004-02-03'
insert into table1(date1) select '2004-03-05'
insert into table1(date1) select '2004-03-11'
insert into table1(date1) select '2004-04-09'

--sql语句
select top 2 * from table1 where id>=
(select top 1 a.id from table1 a join table1 b on a.id=b.id-1 order by abs(datediff(day,a.date1,b.date1)) desc)
order by id
wyb0026 2005-04-12
  • 打赏
  • 举报
回复
mark
hsj20041004 2005-04-12
  • 打赏
  • 举报
回复
你找出一个最大的date1
再找出一个最小的date1
俩个相差的时间当然最大了
select * from table1 where date1=(select max(date1) from table1)
select * from table1 where date1=(select min(date1) from table1)

27,579

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 应用实例
社区管理员
  • 应用实例社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧