2014-10-27 29 views
3
個月

說我有包含我的用戶訂閱的期限內,如表:計算值按比例在與Oracle

user product value start_date end_date 
Scott T23K  250  15/01/2014 15/02/2015 
Tiger T23K  200  05/01/2014 05/02/2015 
Scott T00Z  20  10/01/2014 02/02/2015 
... 

我想根據我的結算週期(每月一次),以增加收入報告中指出,看起來像:

month  product value 
Jan/2014 T23K  275 
Jan/2014 T00Z  19.1 
Feb/2014 T23K  275 
Feb/2014 T00Z  0.9 

我想我能查詢like this,但我在想,如果沒有一個聰明的解析函數或一些會使其看起來更好。想法?

我使用的是Oracle 11gR2的

+0

如何值0.9 T00Z /月計算? – 2014-10-27 14:45:39

+0

T00Z爲期23天,1月爲21天,2月爲2天,因此1月份花費約95%(19.1美元),2月花費約5%(0.9美元)。 – filippo 2014-10-27 15:16:46

回答

1

試試這個,我覺得你的情況相符:

with subscriptions as 
(
select 'Scott' user_, 'T23K' product , '250' value , to_date('15/01/2014','DD/MM/YYYY') start_date , to_date('15/02/2015','DD/MM/YYYY') end_date from dual 
union all 
select 'Tiger' user_, 'T23K' product , '200' value , to_date('05/01/2014','DD/MM/YYYY') start_date , to_date('05/02/2015','DD/MM/YYYY') end_date from dual 
union all 
select 'Scott' user_, 'T00Z' product , '20' value , to_date('10/01/2014','DD/MM/YYYY') start_date , to_date('02/02/2014','DD/MM/YYYY') end_date from dual 
) 
, allMonts as 
(select add_months(to_date('01/01/2010','DD/MM/YYYY'),rownum) myMonth , lag(add_months(to_date('01/01/2010','DD/MM/YYYY'),rownum)) over (order by rownum desc) -add_months(to_date('01/01/2010','DD/MM/YYYY'),rownum) daymonth from dual CONNECT BY LEVEL <= 100 
) 
, detail as 
(
select s.*,allMonts.myMonth, end_date-start_date duration, 
     case when trunc(start_date,'MON')=trunc(end_date,'MON') then (end_date-start_date)*value/(end_date-start_date) 
      when trunc(start_date,'MON')=allMonts.myMonth then (add_months(allMonts.myMonth,1) - start_date)*value/(end_date-start_date) 
      when trunc(end_date,'MON')=allMonts.myMonth then (end_date - allMonts.myMonth)*value/(end_date-start_date) 
      else allMonts.daymonth*value/(end_date-start_date) 
      end value_by_month 
from subscriptions s , allMonts 
where allMonts.myMonth 
between trunc(s.start_date,'MON') and trunc(s.end_date,'MON')+1 
) 
select myMonth, product, sum(value_by_month) 
from detail 
group by rollup(myMonth), product