【问题标题】:Oracle SQL : Getting average for past 3 month and add additional columnOracle SQL:获取过去 3 个月的平均值并添加额外的列
【发布时间】:2016-01-19 16:07:26
【问题描述】:

我在 Oracle 中有下表,我需要从该表中创建一个视图来计算附加列中过去 3 个月的平均分数。

Name      YearMonth     Score
Vince     201507         97
Vince     201508         95
Vince     201509         94
Vince     201510         91
Vince     201511         98
Vince     201512         95
Vince     201501         93     

预期输出:

Name      YearMonth     Score   Average
Vince     201507         97      
Vince     201508         95        
Vince     201509         94      95.33 ((97+95+94)/3)
Vince     201510         91      93.33 ((95+94+91)/3)
Vince     201511         98      94.33 ((94+91+98)/3)
Vince     201512         95      94.67 ((91+98+95)/3)
Vince     201501         93      95.33 ((98+95+93)/3)

我怎样才能使用 SQL 来做到这一点?感谢您的帮助

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    您可以使用窗口函数来做到这一点:

    select name, 
           yearmonth, 
           score,
           avg(score) over (order by to_date(yearmonth, 'yyyymm') range between interval '3' month preceding and current row) as average
    from scores;
    

    以上假设yearmonthvarchar 列,否则to_date() 将不起作用。

    这不是确切您的示例输出,因为前两行的平均值等于该行的分数(因为这两行没有前 3 个月)。如果您确实需要这些平均值为空,您可以执行以下操作:

    select name, 
           yearmonth, 
           score,
           case 
             when row_number() over (order by to_date(yearmonth, 'yyyymm')) > 2 then
                 avg(score) over (order by to_date(yearmonth, 'yyyymm') range between interval '3' month preceding and current row) 
             else null -- not really necessary, just for clarity
           end as average
    from scores;
    

    【讨论】:

    • 感谢您的回答。只是跟进,可以将查询修改为过去 3 周,而不是几个月?我也需要一个星期,YearMonth 列将被 YearWeek 列替换。提前谢谢你。
    • @lanthe,请改用interval '21' day。如果您有 yearweek 列,则 Dmitry 的解决方案将持续三周而不会发生任何变化。
    【解决方案2】:
    select name, year_month, score,
           (score +
            lag(score, 1) over (partition by name, year_month order by score) +
            lag(score, 2) over (partition by name, year_month order by score)) / 3 average
      from my_table
    

    【讨论】:

      猜你喜欢
      • 2019-03-03
      • 1970-01-01
      • 2019-05-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多