oracle sql中的日级计算

时间:2018-02-06 07:34:44

标签: sql sql-server oracle oracle11g

我有两年的静态数据。我的列名为stats_date,P2P_volume。最初我在oracle sql developer中创建了以下查询单日

选择' 1'作为KPI_ID,' P2P'作为KPI_DESC,' 22-MAR-17'作为日期,  (总和(在add_months之间的STATS_DATE时的情况(' 22-MAR-17',0)-13     和add_months(' 22-MAR-17',0)-7然后P2P_VOLUME其他0结束)) LAST_WEEK_Volume,

  (sum(case when STATS_DATE between add_months('22-MAR-17',0)-6
and add_months('22-MAR-17',0)  then P2P_VOLUME else 0 end )) THIS_WEEK_Volume from table

我的问题是我想要创建动态查询,它会给我Last_week_volume,而this_week_volume日期明智两年。而不是单日

1 个答案:

答案 0 :(得分:0)

在没有完整的样本数据和要求的情况下,我的假设是:

  1. 每个KPI每天有一行
  2. 可以满足current weekprevious week的定义 使用'IW'日期格式掩码
  3. 此解决方案使用子查询来计算每周度量的总和。这将输入主查询,该查询使用分析lag()函数来显示当前周和前一周的总计。

    with cte as (
      select kpi
            , to_char(static_date, 'YYYY') as yr
           , to_char(static_date, 'IW') as wk
           , sum(volume) as wk_volume
           , sum(value) as wk_value
           , sum(revenue) as wk_revenue
      from t23
      group by kpi,to_char(static_date, 'YYYY'), to_char(static_date, 'IW')
    )
    select kpi
           , yr||'-'||wk as year_wk
           , wk_volume as curr_wk_volume
           , lag(wk_volume) over (order by yr, wk) as prev_wk_volume
           , wk_value as curr_wk_value
           , lag(wk_value) over (order by yr, wk) as prev_wk_value
           , wk_revenue as curr_wk_revenue
           , lag(wk_revenue) over (order by yr, wk) as prev_wk_revenue
    from cte
    order by 1, 2
    /
    

    a SQL Fiddle demo here