Oracle第一季度与第二季度的收入增长

时间:2019-12-18 14:35:19

标签: oracle

计算甲骨文第一季度与第二季度的收入增长-> 我有一个销售表,其销售额为dt_invoice_date列。我使用了此自联接查询-

select
  yr1,qtr2, qtr1, sales1,sales2, (sales1-sales2)/sales2*100 as growth
from (
  select
   extract(year from dt_invoice_date) yr1,
   TRUNC(EXTRACT(MONTH FROM dt_invoice_date) / 3) qtr1,
   sum(sale_value) as sales1
  from base_sales_data_tbl  
  group by extract(year from dt_invoice_date),
        TRUNC(EXTRACT(MONTH FROM dt_invoice_date) / 3)
) S1
left outer join
 (
   select
    extract(year from dt_invoice_date)  yr2, 
    TRUNC(EXTRACT(MONTH FROM dt_invoice_date) / 3) qtr2,
    sum(sale_value) as sales2
   from base_sales_data_tbl 
   group by extract(year from dt_invoice_date),
         TRUNC(EXTRACT(MONTH FROM dt_invoice_date) / 3)
) S2 ON (yr1 = yr2 AND qtr2-1 = qtr1)
where qtr1= 1 and qtr2= 2
order by yr1;

现在,这给了我答案,但这需要时间。因此,我尝试使用递归查询->

   with s1 as (
      select
         sum(s.sale_value) sales,
         to_char(dt_invoice_date,'yyyyq') yrq, 
         lag(sum(s.sale_value),1) over (order by to_char(dt_invoice_date,'yyyyq')) sales_pq
      from base_sales_data_tbl s
      where to_char (dt_invoice_date,'q') <3 
      group by to_char(dt_invoice_date,'yyyyq')
  )
  select
     yrq,
     lag(yrq,1) over (order by yrq) prev_q,
     sales, sales_pq, round((sales-sales_pq)*100/sales_pq,2) growth
  from s1
  order by yrq;

但是我得到的结果是这样的

enter image description here

在这里,我想比较同一年的qtr1与qtr 2收入。该查询为我提供了我不需要的2015年第1季度与2014年第2季度的收入增长。请帮助。

2 个答案:

答案 0 :(得分:0)

有一个很小的错误。

您需要在partition by函数中使用lag子句。

类似这样的东西:

lag(sum(s.sale_value),1) over (partition by trunc(dt_invoice_date,'YEAR') order by to_char(dt_invoice_date,'yyyyq')) sales_pq

并在group by子句中使用相同的内容。

group by trunc(dt_invoice_date,'YEAR'),
 to_char(dt_invoice_date,'yyyyq'))

干杯!

答案 1 :(得分:0)

通过比较yearq和prev_q,您可以轻松地从结果中过滤数据,但是还有一些枢轴可以帮助您:

select yr, q1, q2, q2/q1 - 1 as growth
  from (select sale_value, to_char(dt_invoice_date, 'yyyy') yr, to_char(dt_invoice_date, 'q') q 
          from base_sales_data_tbl 
          where to_char(dt_invoice_date, 'q') < 3)
  pivot (sum(sale_value) for q in (1 q1, 2 q2))

demo