Mega Code Archive

 
Categories / Oracle PLSQL / Analytical Functions
 

Row-ordering is done first and then the moving average

SQL> create table TestTable (   2    x    number primary key,   3    y   number   4  ); Table created. SQL> SQL> insert into TestTable values (1, 7 ); 1 row created. SQL> insert into TestTable values (2, 1 ); 1 row created. SQL> insert into TestTable values (3, 2 ); 1 row created. SQL> insert into TestTable values (4, 5 ); 1 row created. SQL> insert into TestTable values (5, 7 ); 1 row created. SQL> insert into TestTable values (6, 34 ); 1 row created. SQL> insert into TestTable values (7, 32 ); 1 row created. SQL> insert into TestTable values (8, 43 ); 1 row created. SQL> insert into TestTable values (9, 87 ); 1 row created. SQL> insert into TestTable values (10, 32 ); 1 row created. SQL> insert into TestTable values (11, 12 ); 1 row created. SQL> insert into TestTable values (12, 16 ); 1 row created. SQL> insert into TestTable values (13, 63 ); 1 row created. SQL> insert into TestTable values (14, 74 ); 1 row created. SQL> insert into TestTable values (15, 36 ); 1 row created. SQL> insert into TestTable values (16, 56 ); 1 row created. SQL> insert into TestTable values (17, 2 ); 1 row created. SQL> SQL> select * from TestTable;          X          Y ---------- ----------          1          7          2          1          3          2          4          5          5          7          6         34          7         32          8         43          9         87         10         32         11         12         12         16         13         63         14         74         15         36         16         56         17          2 17 rows selected. SQL> SQL> SQL> -- Row-ordering is done first and then the moving average: SQL> SQL> SELECT x, y,   2    AVG(y) OVER(ORDER BY y   3      ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING) ma   4  FROM TestTable   5  ORDER BY y;          X          Y         MA ---------- ---------- ----------          2          1        1.5          3          2 1.66666667         17          2          3          4          5 4.66666667          1          7 6.33333333          5          7 8.66666667         11         12 11.6666667         12         16         20          7         32 26.6666667         10         32 32.6666667          6         34         34         15         36 37.6666667          8         43         45         16         56         54         13         63 64.3333333         14         74 74.6666667          9         87       80.5 17 rows selected. SQL> SQL> SQL> SQL> drop table TestTable; Table dropped. SQL> SQL>