如果使用Sqplus在10天之内没有数据,如何获取90天的数据?

问题描述 投票:1回答:1

我编写了一个查询以从表中获取数据10天。如果10天没有数据,那么我需要提取50天。但是我不知道如何修改查询以获取90天的数据。

Query:

Select ep.NAME||'|'||s.id||'|'||s.SUBMISSION_DATE||'|'||E.VALUE
from SUMMARY_EXT e, summary s, enterprise ep
where e.id = id and e.name_res_key = 'Plan'
and s.id in (select id from summary where 
trunc(start_date) > trunc(sysdate) -10 and service_name ='Dplan')

我想修改我的查询,就好像有10天的数据,那么它应该获取10天。如果没有数据,则应获取90天。

oracle sqlplus
1个回答
0
投票

分析函数可以根据其他行的存在来帮助返回行。首先,使用CASE表达式将行分类为10天,50天或90天存储桶。然后使用分析函数计算每个组中的行数。最后,仅根据这些计数从相关组中选择。

例如:

-- Return 10 days, 50 days, or 90 days of data.
--
--#3: Only return certain rows depending on the counts.
select id, start_date
from
(
    --#2: Count the number of rows in each category.
    select id, start_date, is_lt_10, is_lt_50, is_lt_90
        ,sum(is_lt_10) over () total_lt_10
        ,sum(is_lt_50) over () total_lt_50
        ,sum(is_lt_90) over () total_lt_90
    from
    (
        --#1: Put each row into a date category.
        select
            id, start_date,
            case when trunc(start_date) > trunc(sysdate) - 10 then 1 else 0 end is_lt_10,
            case when trunc(start_date) > trunc(sysdate) - 50 then 1 else 0 end is_lt_50,
            case when trunc(start_date) > trunc(sysdate) - 90 then 1 else 0 end is_lt_90
        from summary
        where start_date > trunc(sysdate) - 90
    )
)
where
    (is_lt_10 = 1 and total_lt_10 > 0) or
    (is_lt_50 = 1 and total_lt_10 = 0 and total_lt_50 > 0) or
    (is_lt_90 = 1 and total_lt_50 = 0 and total_lt_90 > 0);

下面的视图可以帮助模拟日期范围。对于像这样的复杂查询,从尽可能简单的开始,然后在以后添加所有其他联接和列会很有帮助。

--Data for 10 days only.
create or replace view summary as
select 1 id, sysdate    start_date from dual union all
select 2 id, sysdate-49 start_date from dual union all
select 3 id, sysdate-89 start_date from dual union all
select 4 id, sysdate-99 start_date from dual;

--Data for 50 days only.
create or replace view summary as
select 2 id, sysdate-49 start_date from dual union all
select 3 id, sysdate-89 start_date from dual union all
select 4 id, sysdate-99 start_date from dual;

--Data for 90 days only.
create or replace view summary as
select 3 id, sysdate-89 start_date from dual union all
select 4 id, sysdate-99 start_date from dual;
© www.soinside.com 2019 - 2024. All rights reserved.