【问题标题】:oracle month to day甲骨文每月
【发布时间】:2014-09-11 00:01:36
【问题描述】:

我有如下数据,其中数据拆分如下,其中第 1 个月代表 JAN,第 2 个月代表 FEB,依此类推。

MONTH   VALUE
1        93
2        56
3       186
4        60

现在我需要根据天数计算价值总和。

Ex- 如果日期在 1 月 1 日至 3 月 31 日之间,则 SUM 为 335(93+56+186)

如果日期在 1 月 17 日至 3 月 31 日之间,则总和为 287(45+56+186)。

这里 1 月份的 45 是从 1 月份 (93/31==3) 的平均每天得出的。乘以所需时间段的 1 月份天数。

忽略闰年和 FEB 月总是可以取 28 天。

【问题讨论】:

    标签: sql oracle oracle11g date-arithmetic


    【解决方案1】:

    作为其中一种方法,您可以将一个月转换为构成它的天(日期)列表(简化过滤操作),并进行如下计算:

    /* 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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-05
      • 2011-07-19
      • 2011-06-15
      • 2020-06-10
      • 2018-08-20
      相关资源
      最近更新 更多