SQL 更新列的语句

SQL statement to update a column

我有一个 Table T1 具有以下值

我需要一个带有附加列的结果 table,该列是最新的平均值。 即

x1= 1000.45

x2= (1000.45+2000.00)/2

x3= (1000.45+2000.00+3000.50)/3

x4= (1000.45+2000.00+3000.50+4000.24)/4

结果 table 应如下所示:

我需要在 Oracle 数据库中编写 SQL 语句以将列添加到结果 table 中,列值为 x1、x2、x3、x4。

您需要为此使用解析函数。我未经测试的SQL如下:

SELECT
 date,
 division,
 sum_sales,
 AVG( sum_sales ) OVER ( ORDER BY date ROWS UNBOUNDED PRECEDING )
FROM
 table;

date 是 Oracle 中的保留字,因此如果您将其用作真实的列名,则需要将其包含在引号中。

select date,division,sum_sales,avg(sum_sales) over ( order by sum_sales ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
from table
group by date,division,sum_sales

您需要使用AVG function OVER ordering by date. As each row is an aggregation result of all the preceding rows, you need to define the window of the aggregation as UNBOUNDED PRECEDING

遵循这些准则,结果语句如下:

SELECT date_d, 
       division, 
       sum_sales, 
       AVG(sum_sales) 
         over ( 
           ORDER BY date_d ROWS unbounded preceding ) avrg 
FROM   supplier; 

您可以在 FIDDLE

中进行测试

这两篇文章中关于解析函数的两个好资料:
Introduction to Analytic Functions (Part 1)
Introduction to Analytic Functions (Part 2)