首页
学习
活动
专区
圈层
工具
发布

甲骨文
EN

Stack Overflow用户
提问于 2014-07-20 08:53:46
回答 1查看 185关注 0票数 2

我有如下数据,其中数据被分割成下面的数据,其中月份1表示一月,月份2表示2月,等等。

代码语言:javascript
复制
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天。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-07-20 10:01:52

作为其中一种方法,您可以将一个月转换为组成它的天数(日期)列表(轻松过滤操作),并按以下方式执行计算:

代码语言:javascript
复制
/* 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

结果:

代码语言:javascript
复制
    RESULT
----------
       287 
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24848880

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档