Sql firebird 2.5选择日期最接近今天的记录
我有一个列为:id,date的查询结果/表。比如: 身份证,日期 0001 , 2012.01.20 0001 , 2014.10.12 0001,空 0001 , 2017.05.21 0001 , 2017.08.15 0002,空 0002 , 2013.06.05 0002 , 2017.08.11 0003,空 0004 , 2011.12.25 0005 , 2017.12.10 0006,空 0006 , 2013.04.23 . . . 等 这就是一个例子——在现实世界中,有几千个id和超过150万条记录。如何查找最接近今天的未来日期id为0001、0002、0005的记录,并且这些记录仅具有null id 0003、过去日期id 0004或null,并且过去日期id 0006替换为一些文本。结果应该如下所示: 身份证,日期 0001 , 2017.05.21 0002 , 2017.08.11 0003,“替换文本” 0004,“替换文本” 0005 , 2017.12.10 0006,“替换文本” . . 等 我希望这个例子正好说明我需要什么。Sql firebird 2.5选择日期最接近今天的记录,sql,firebird,firebird2.5,Sql,Firebird,Firebird2.5,我有一个列为:id,date的查询结果/表。比如: 身份证,日期 0001 , 2012.01.20 0001 , 2014.10.12 0001,空 0001 , 2017.05.21 0001 , 2017.08.15 0002,空 0002 , 2013.06.05 0002 , 2017.08.11 0003,空 0004 , 2011.12.25 0005 , 2017.12.10 0006,空 0006 , 2013.04.23 . . . 等 这就是一个例子——在
感谢您提供的任何线索。该表似乎没有主键。 不要使用字段名作为类型名,如日期 无论如何,这里有一个例子,如何做到这一点,你想,没有声称这是最好的 请注意,如果有许多记录,此过程将很慢,因此请确保放置了正确的索引 结果是:
所以这不是一个“我的代码”——服务。你尝试了什么?你被困在哪里?
SET TERM ^ ;
create or alter procedure TEMP_TEST_PROC (
IDATE date)
returns (
OID varchar(4),
DATE_BEFORE date,
DATE_AFTER date,
CLOSEST_DATE date,
OTEXT varchar(32))
as
begin
for select distinct id from test_table_wo_pk
into :oid
do
begin
date_before = null;
date_after = null;
/* get closest past date*/
select first 1 t."DATE" from test_table_wo_pk t
where ((t."DATE" <= :idate) and (t.id = :oid))
order by t."DATE" desc
into
:date_before;
/* get closest future date*/
select first 1 t."DATE" from test_table_wo_pk t
where (t."DATE" >= :idate) and (t.id = :oid)
order by t."DATE"
into
:date_after;
/* bonus - get closest future or past date */
... You may check date_before, date_after for NULL here, and set closest_date value here....
if ((datediff(day,:date_before,:idate)) < (datediff(day,:idate,date_after))) then
closest_date = :date_before;
else
closest_date = :date_after;
/* set text column */
if (:date_after is not null) then
otext = :date_after;
else
otext = 'replased text';
suspend;
end
end^
SET TERM ; ^