PL/SQL 输出给定日期行的程序,如果不存在,应给出最新日期

PL/SQL procedure to output line the given date if not existing, latest date should be given

我有这个 table 信息值,其内容为:

现在我创建了一个过程,我需要输入一个日期参数,该参数应该输出正确的 attr 行和给定的 price。如果日期不存在,则最新日期应为 selected.

to_date('01-jan-19') 的解决方案 table 如下所示:

这将是过程中的输出行。

我应该 select 更正元组并输出它的行,还是最好只是批量收集所有内容,然后使用 if 语句检查 for 循环我需要显示什么元组。

我目前拥有的:

包含我要查找的元组的 select 语句:

create or replace procedure print_inf_value(closingDate Date) is
cursor d1 (closingDate Date) is
select t.attr, t.dateOfValue, t.price
from ( 
  select i.*,
    row_number() over (
      partition by attr 
      order by case when dateOfValue = closingdate then 1 else 2 end, dateOfValue desc
    ) rn
  from InformationValues i
) t
where t.rn = 1;

BEGIN

dbms_output.put_line('Information             Value   ');
dbms_output.put_line('--------------------------------');
FOR d1_rec IN d1 LOOP
        dbms_output.put_line(d1_rec.attr || '             ' || d1_rec.price );
END LOOP;

END;

或者我批量收集所有内容然后我需要整理出我需要的元组的过程:

create or replace procedure print_inf_value(closingDate Date) is
TYPE d1 IS TABLE OF informationvalues%rowtype;
emps d1; 

begin select * bulk collect into emps 
from informationvalues;

FOR i IN 1 .. emps.COUNT LOOP
if emps(i).dateofvalue = closingDate then
dbms_output.put_line(emps(i).attr || '             ' || emps(i).price );
/*else*/

end if;
END LOOP;
END;

两者都无法正常工作,所以我缺少什么来显示具有正确日期的元组。

请尝试:

CREATE OR REPLACE PROCEDURE print_inf_value (closingDate DATE)
IS
BEGIN
   DBMS_OUTPUT.put_line (RPAD ('ATTR', 20) || RPAD ('PRICE', 20));

   FOR o
      IN (select attr, trim(case when price < 1 then to_char(price,90.9) else to_char(price) end) price from (
            select attr, price, dateofvalue,
            row_number() over (partition by attr order by dateofvalue desc) rn from informationvalues
            ) i where dateofvalue = closingdate
            or (rn = 1 and not exists (select 1 from informationvalues iv where iv.attr = i.attr and dateofvalue = closingdate) ) 
        )
   LOOP
      DBMS_OUTPUT.put_line (RPAD (o.attr, 20) || RPAD ( o.price, 20));
   END LOOP;
END;

示例执行:

set serveroutput on;

begin
    print_inf_value(date'2019-01-01');
end;

输出:

ATTR                PRICE               
age                 2                   
electronics         0.5               
gender              3                   
hobbies             0.5               
homeAddress         7                   
maritalStatus       1                   
mobilePhone         5                   
musicTaste          0.1               
socialContacts      1