SQL Oracle Query自我查询

时间:2015-08-03 14:14:58

标签: sql oracle

我正在尝试弄清楚如何使用1.245填充以下NULL值,从07-OCT-1429-SEP-14,然后从26-SEP-1428-JUL-14,它将是1.447。

这意味着如果日期小于或等于给定日期,则使用最大生效日期的值小于给定日期

我们可以为给定的security_alias和生效日期< = p.effective_date选择最后一个可用的index_ratio值,所以换句话说我们需要修改sql以从子查询返回为最大可用有效性确定的索引比率值日期假设该生效日期小于或等于职位生效日期

如何填充价值?

select ab.security_alias,
ab.index_ratio,
ab.effective_date
from securitydbo.security_analytics_fi ab 
where ab.security_alias = 123627
order by ab.effective_date desc

enter image description here

下面应该是输出

enter image description here

1 个答案:

答案 0 :(得分:0)

假设我正确理解您的要求,我认为分析函数LAST_VALUE()就是您所追求的。 E.g:

with sample_data as (select 1 id, 10 val, to_date('01/08/2015', 'dd/mm/yyyy') dt from dual union all
                     select 1 id, null val, to_date('02/08/2015', 'dd/mm/yyyy') dt from dual union all
                     select 1 id, null val, to_date('03/08/2015', 'dd/mm/yyyy') dt from dual union all
                     select 1 id, null val, to_date('04/08/2015', 'dd/mm/yyyy') dt from dual union all
                     select 1 id, 20 val, to_date('05/08/2015', 'dd/mm/yyyy') dt from dual union all
                     select 1 id, 21 val, to_date('06/08/2015', 'dd/mm/yyyy') dt from dual union all
                     select 1 id, null val, to_date('07/08/2015', 'dd/mm/yyyy') dt from dual union all
                     select 1 id, null val, to_date('08/08/2015', 'dd/mm/yyyy') dt from dual union all
                     select 1 id, 31 val, to_date('09/08/2015', 'dd/mm/yyyy') dt from dual union all
                     select 1 id, null val, to_date('10/08/2015', 'dd/mm/yyyy') dt from dual union all
                     select 1 id, 42 val, to_date('11/08/2015', 'dd/mm/yyyy') dt from dual)
select id,
       last_value(val ignore nulls) over (partition by id order by dt) val,
       dt
from   sample_data
order by id, dt desc;

        ID        VAL DT        
---------- ---------- ----------
         1         42 11/08/2015
         1         31 10/08/2015
         1         31 09/08/2015
         1         21 08/08/2015
         1         21 07/08/2015
         1         21 06/08/2015
         1         20 05/08/2015
         1         10 04/08/2015
         1         10 03/08/2015
         1         10 02/08/2015
         1         10 01/08/2015