求区间内最近的时间
时间:2011-11-20
来源:互联网
create table t(id date); insert into t select '2010-9-3' union all select '2010-9-1' union all select '2010-9-5' union all select '2010-9-22';
求距离 '2010-9-1'最近的时间。
小弟第一次发帖,也不知道自己有多少分,求高手解决。
作者: down_login 发布时间: 2011-11-20
作者: down_login 发布时间: 2011-11-20
select top 1 * from t order by abs(datediff(dd,id,'2010-09-03'))
作者: fredrickhu 发布时间: 2011-11-20
create table t(id datetime); insert into t select '2010-9-3' union all select '2010-9-1' union all select '2010-9-5' union all select '2010-9-22'; go declare @dt datetime set @dt='2010-9-3' select top 1 * from t where id<>@dt order by abs(datediff(d,id,@dt)) /* id ----------------------- 2010-09-05 00:00:00.000 (1 行受影响) */ go drop table t
作者: qianjin036a 发布时间: 2011-11-20
不好意思,错了,应该是求距离 '2010-9-3'最近的时间。语句该怎么写?
最近的时间不就是 2010-09-03么?
作者: fredrickhu 发布时间: 2011-11-20
SQL code
create table t(id datetime);
insert into t
select '2010-9-3'
union all
select '2010-9-1'
union all
select '2010-9-5'
union all
select '2010-9-22';
go
declare @dt datetime
set @dt=……
恩 也许就是这个意思。
作者: fredrickhu 发布时间: 2011-11-20
'2010-9-3','2010-9-5','2010-9-22'。在这些已知的时间内,求距离各个时间最近的时间,例如距离 '2010-9-1'最近的是 '2010-9-3',距离相差两天,而距离 '2010-9-3'最近的是 '2010-9-1'和'2010-9-5',距离都是相差两天,距离 '2010-9-22'最近的是 '2010-9-5'了。
还麻烦能解释下order by abs(datediff(d,id,@dt))这句吗?
作者: down_login 发布时间: 2011-11-20
我的意思是存在一个离散的时间区间,例如 '2010-9-1'到 '2010-9-22',现有时间数据 '2010-9-1'
'2010-9-3','2010-9-5','2010-9-22'。在这些已知的时间内,求距离各个时间最近的时间,例如距离 '2010-9-1'最近的是 '2010-9-3',距离相差两天,而距离 '2010-9-3'最近的是 '2010-9-1'和'2010-9-5',……
还麻烦能解释下order by abs(datediff(d,id,@dt))这句吗?
我以为你是要指定一个日期的,那就是以这个日期为标准,拿其他日期与该日期的天数相减,得到的结果取绝对值,那最小的,就用 top 1 取出来.
作者: qianjin036a 发布时间: 2011-11-20
create table t(id datetime); insert into t select '2010-9-3' union all select '2010-9-1' union all select '2010-9-5' union all select '2010-9-22'; go select id,(select top 1 id from t where id<>a.id order by abs(datediff(d,id,a.id)))as latestid from t a /* id latestid ----------------------- ----------------------- 2010-09-03 00:00:00.000 2010-09-05 00:00:00.000 2010-09-01 00:00:00.000 2010-09-03 00:00:00.000 2010-09-05 00:00:00.000 2010-09-03 00:00:00.000 2010-09-22 00:00:00.000 2010-09-05 00:00:00.000 (4 行受影响) */ go drop table t
作者: qianjin036a 发布时间: 2011-11-20
热门阅读
-
office 2019专业增强版最新2021版激活秘钥/序列号/激活码推荐 附激活工具
阅读:74
-
如何安装mysql8.0
阅读:31
-
Word快速设置标题样式步骤详解
阅读:28
-
20+道必知必会的Vue面试题(附答案解析)
阅读:37
-
HTML如何制作表单
阅读:22
-
百词斩可以改天数吗?当然可以,4个步骤轻松修改天数!
阅读:31
-
ET文件格式和XLS格式文件之间如何转化?
阅读:24
-
react和vue的区别及优缺点是什么
阅读:121
-
支付宝人脸识别如何关闭?
阅读:21
-
腾讯微云怎么修改照片或视频备份路径?
阅读:28