Oracle SQL到给定日期的最接近日期

问题描述 投票:0回答:2

我有一个表格,其中包含类别,日期和价格的列。像这样:

group 1  - 03.03.2019 - 5.00
group 1  - 03.02.2018 - 4.00
group 2  - 05.05.2019 - 2.25
group 2  - 05.05.2018 - 1.00

因此,每个组(几乎)总是有两个日期,价格不同。现在我需要编写一个SQL语句以使每个组的日期最接近给定日期(例如05.05.2019)。第1组有两个日期,SQL语句需要选择两个日期中最接近给定日期的一个。所有组都需要这样做。

我尝试了几个小时,但被卡住了。感谢您的帮助

编辑:

好吧,到目前为止,它仍然可以正常工作,但是我忘了写的是这是PL SQL作业,我需要用光标将其打印出来。

到目前为止,这是我的代码:

Procedure print_inf_value(closingDate Date) AS

    counter number := 1;
    attr_out varchar2(200);
    value_out varchar2(200);

    CURSOR c1 IS 
        select t.attr
        from informationvalues t
        where 
            t.dateofValue <= closingDate
            and not exists (
                select 1
                from informationvalues t1
                where t1.attr = t.attr and t1.dateofValue <= closingDate and t1.dateofValue > t.dateofValue
    );              

     CURSOR c2 IS 
        select t.price
        from informationvalues t
        where 
            t.dateofValue <= closingDate
            and not exists (
                select 1
                from informationvalues t1
                where t1.attr = t.attr and t1.dateofValue <= closingDate and t1.dateofValue > t.dateofValue); 

    BEGIN
    WHILE counter <= 10 LOOP
        OPEN c1;
        FETCH c1 INTO attr_out;
        CLOSE c1;

        OPEN c2;
        FETCH c2 INTO value_out;
            dbms_output.put_line('Attr: ' ||attr_out || '    Price: ' || value_out);
        CLOSE c2;
        counter := counter + 1;
     END LOOP; 
END print_inf_value;

Informationvalues是表,attr是类别。现在的输出是:

Attr: maritalStatus    Price: 1
Attr: maritalStatus    Price: 1
Attr: maritalStatus    Price: 1
Attr: maritalStatus    Price: 1
Attr: maritalStatus    Price: 1
Attr: maritalStatus    Price: 1
Attr: maritalStatus    Price: 1
Attr: maritalStatus    Price: 1
Attr: maritalStatus    Price: 1
Attr: maritalStatus    Price: 1

因此,它仅打印一种类别+正确的价格(从正确的日期开始),但是打印10次。

sql oracle date closest
2个回答
1
投票

这里是使用not exists的一个选项:


0
投票

您也许可以在这里使用排名功能

© www.soinside.com 2019 - 2024. All rights reserved.