Oracle DB-单查询非线性时间分组报告(总共1天,1周,1个月,3个月)

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

我正在尝试构建一个本质上是将这些查询的输出组合在一起的单个查询的报告:

select count(*) from my_table where createddate >= CURRENT_DATE - 1;
select count(*) from my_table where createddate >= CURRENT_DATE - 7;
select count(*) from my_table where createddate >= CURRENT_DATE - 30;
select count(*) from my_table where createddate >= CURRENT_DATE - 90;
select count(*) from my_table;

这样输出将类似于:

Time_Period   Count
===================
Yesterday        5
Last Week       20
Last Month      50
Last 90 Days   100
Total         5000

我已经成功构建了几个线性时间序列查询(按天,按周,按月等)。但是,能够构建非线性报告查询并不算运气。

sql oracle date plsql reporting
3个回答
1
投票

您可以轻松地将结果放在单独的列中:

select sum(case when createddate >= CURRENT_DATE - 1 then 1 else 0 end) as yesterday,
       sum(case when createddate >= CURRENT_DATE - 7 then 1 else 0 end) as last_week,
       sum(case when createddate >= CURRENT_DATE - 30 then 1 else 0 end) as last_month,
       sum(case when createddate >= CURRENT_DATE - 90 then 1 else 0 end) as last_90days,
       count(*) as total
from my_table;

如果要单独的行,则可以取消以上内容的透视图,或只使用union all

select 'Yesterday' as which, count(*) from my_table where createddate >= CURRENT_DATE - 1
union all
select 'Last week', count(*) from my_table where createddate >= CURRENT_DATE - 7
union all
select 'Last month', count(*) from my_table where createddate >= CURRENT_DATE - 30
union all
select 'Last 90 days', count(*) from my_table where createddate >= CURRENT_DATE - 90
union all
select 'Total', count(*) from my_table;

0
投票

您可以将偏移量用union all放在行中,然后将left join放在表中,如:

select
    o.time_period,
    count(t.created) cnt
from (
    select 'yesterday' time_period, 1 offs
    union all select 'last week', 7
    union all select 'last month', 30
    union all select 'last 90 days', 90
    union all select 'total', null
) o
left join mytable t on o.offs is null or t.created >= current_date - o.offs
group by o.time_period

0
投票

一种选择是在PL / SQL中使用动态查询,以及为日周期定义数组及其字面解释:

SQL> set serveroutput on
SQL> declare  
 v_sql    varchar2(250):='select count(*) from my_table where createddate >= current_date - :day'; 
 v_prd    owa.nc_arr;
 v_str    owa.vc_arr;   
 v_amount int;
begin
 v_prd(1) := 1;  v_prd(2) := 7; v_prd(3) := 30; v_prd(4) := 90; v_prd(5) := 100000;
 v_str(1) := 'Yesterday';  v_str(2) := 'Last Week'; v_str(3) := 'Last Month'; 
 v_str(4) := 'Last 90 Days'; v_str(5) := 'Total';   

     dbms_output.put_line('Time_Period   Count');
     dbms_output.put_line('===================');  
 for i in 1..5 
 loop
     execute immediate v_sql into v_amount using v_prd(i); 
     dbms_output.put_line(rpad(v_str(i),14,' ')||v_amount);  
 end loop;   
end;  
/

其中v_prd(5)值可能尽可能大以包含表的所有记录。

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