请参考如下SQL,具体逻辑是:差值的绝对值小到大排序,取第一行即可。
如果需要其他列的值,把取值放where中…… 这样就算有重复值(差值的绝对值相同)也能揪出来~
select T from table(select T, abs($T_STR-T) as diff from A) order by diff fetch first 1 rows only
例子:
db2 => select from a
T
--------------------------
2014-04-02-010000000000
2014-05-02-010000000000
2014-06-02-010000000000
3 record(s) selected
db2 => values timestamp('2014-05-03-01000000000')
1
--------------------------
2014-05-03-010000000000
1 record(s) selected
db2 => select T from table(select T, abs('2014-05-03-01000000000'-T) as diff from A) order by diff fetch first 1 rows only
T
--------------------------
2014-05-02-010000000000
1 record(s) selected
db2 =>
SELECT DATE(LEFT('201202', 4) || '-'||RIGHT('201202', 2)||'-1') - 1 MONTH,
DATE(LEFT('201202', 4) || '-'||RIGHT('201202', 2)||'-1') + 1 MONTH
from sysibm/sysdummy1
DATE(LEFT('201202', 4) || '-'||RIGHT('201202', 2)||'-1') - 1 MONTH这样拿到的是日期类型,需要cast as char,然后截取就可以了
db2处理日期很垃圾的
以上就是关于DB2中,如何查询出与某个时间最接近的记录全部的内容,包括:DB2中,如何查询出与某个时间最接近的记录、关于DB2的日期计算的SQL语句,大神速进、等相关内容解答,如果想了解更多相关内容,可以关注我们,你们的支持是我们更新的动力!
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)