firebird 2.5 选择日期最接近今天的记录

firebird 2.5 selecting records with date closest to today

我的查询 result/table 包含以下列: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)的记录,并且这些记录仅具有空值(id 0003)、过去日期(id 0004)或空值和过去日期(id 0006)替换为一些文本。结果应如下所示:

编号,日期
0001 , 2017.05.21
0002 , 2017.08.11
0003 , 'replaced text'
0004 , 'replaced text'
0005 , 2017.12.10
0006 , 'replaced text'
.
.
等...
我希望这个例子能准确地展示我所需要的。
感谢您提供任何线索。

table 似乎没有主键。 不要使用字段名称作为类型名称,例如 "DATE".

无论如何,这是一个您想要如何做的例子,没有声称它是最好的。

注意,如果有很多记录,此过程会很慢,因此请确保放置正确的索引。

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 ; ^

结果: