我有如下数据,其中数据被分割成下面的数据,其中月份1表示一月,月份2表示2月,等等。
MONTH VALUE
1 93
2 56
3 186
4 60现在我需要根据天数来计算值的总和。
如果日期为1月1日至3月31日,则之和为335(93+56+186)。
如果日期为1月17日至3月31日,则之和为287(45+56+186)。
这里,1月份的45天与1月份的平均日(93/31=3)相比,按1月份所需期间的天数计算。
忽略闰年和二月月都可以取28天。
发布于 2014-07-20 10:01:52
作为其中一种方法,您可以将一个月转换为组成它的天数(日期)列表(轻松过滤操作),并按以下方式执行计算:
/* sample of data that you've provided */
with t1(mnth,val) as(
select 1, 93 from dual union all
select 2, 56 from dual union all
select 3, 186 from dual union all
select 4, 60 from dual
),
/*
Generates current year dates
From January 1st 2014 to December 31st 2014
*/
dates(dt) as(
select trunc(sysdate, 'YEAR') - 1 + level
from dual
connect by extract(year from (trunc(sysdate, 'YEAR') - 1 + level)) <=
extract(year from sysdate)
)
/*
The query that performs calculations based on range of dates
*/
select sum(val / extract(day from last_day(dt))) as result
from dates d
join t1
on (extract(month from d.dt) = t1.mnth)
where dt between date '2014-01-17' and -- January 17th 2014 to
date '2014-03-31' -- March 31st 2014结果:
RESULT
----------
287 https://stackoverflow.com/questions/24848880
复制相似问题