oracle - 使用 Sqplus 10 天没有数据,如何获取 90 天的数据?
问题描述
我编写了一个查询来从表中获取 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 天。
解决方案
分析函数可以帮助根据其他行的存在返回行。首先,使用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;
推荐阅读
- python - 如何用逗号分隔未打包的元组列表
- regex - 正则表达式在 XML 中查找子元素
- listview - 向 ListView 添加新项目时如何更新 UI
- reactjs - 导入的功能组件完成后如何更新反应组件
- node.js - 使用 NodeJS 访问 Dropbox 上的文件
- c# - 使用 multipart/form-data 解析休息响应
- javascript - 是否可以在不使用 for 循环的情况下找到素数?可以仅使用过滤器方法完成吗?
- java - Blob 提交到 DB 的错误是什么?
- powershell - 将变量的结果组合到哈希表中并显示所有值
- flutter - 如何创建始终部分可见的持久底页?