SQL Sequence Cumulative Aggregate Max, Min, Sum, Prd, Avg, Var and Dev Functions

The seq_cum_agg_sum(),seq_cum_agg_min(), seq_cum_agg_prd(), seq_cum_agg_avg(), seq_cum_agg_var(), seq_cum_agg_dev() functions return a sequence with the cumulative maximum (maximum. minimum, etc ... of all preceding elements) in each element.

Following is an example script demonstrating these functions:

 
    SELECT symbol, seq_search(day, 20130101, 20130331) as Q1_13,
            volume@Q1_13 as "Volume_Q1_13",
            seq_cum_agg_max(volume@Q1_13) as "max_Q1_13",
            seq_cum_agg_min(volume@Q1_13) as "min_Q1_13",
            seq_cum_agg_sum(volume@Q1_13) as "sum_Q1_13",
            seq_cum_agg_avg(volume@Q1_13) as "avg_Q1_13",
            seq_cum_agg_var(volume@Q1_13) as "var_Q1_13",
            seq_cum_agg_dev(volume@Q1_13) as "dev_Q1_13"
    FROM Quote WHERE symbol='SYM0';
     
    symbol
    Q1_13{}
    Volume_Q1_13{}
    max_Q1_13{}
    min_Q1_13{}
    sum_Q1_13{}
    prd_Q1_13{}
    avg_Q1_13{}
    var_Q1_13{}
    dev_Q1_13{}
    ------------------------------------------------------------------------------
    SYM0
    {20130101, 20130104, 20130106, 20130110, 20130123, 20130125, 20130129,
      20130213, 20130214, 20130216, 20130311, 20130326}
    {335, 808, 45, 402, 732, 48, 805,
      450, 385, 420, 367, 69}
    {335, 808, 808, 808, 808, 808, 808,
      808, 808, 808, 808, 808}
    {335, 335, 45, 45, 45, 45, 45,
      45, 45, 45, 45, 45}
    {335, 1143, 1188, 1590, 2322, 2370, 3175,
      3625, 4010, 4430, 4797, 4866}
    {335, 270680, 12180600, 4896601200, 3584312078400, 172046979763200, 138497818709376000,
      6983786198090545152, -4466948496734652416, 5449526889820250112, 7728008603400216576,
    -1722984502962053120}
    {335.000000, 571.500000, 396.000000, 397.500000, 464.400000, 395.000000, 453.571429,
      453.125000, 445.555556, 443.000000, 436.090909, 405.500000}
    {0, 55932, 98888, 74173, 77241, 88449, 96397,
      84349, 75435, 67950, 62250, 67356}
    {0, 236, 314, 272, 277, 297, 310,
      290, 274, 260, 249, 259}
         

Each element of the result sequences from the Cum_Agg functions is the cumulative max, min, sum, product average, variance or standard deviation of all of the previous elements in the sequence. These results can be verified using the following table (built with Microsoft Excel version 2010):

Note that seq_cum_agg_prd() very quickly produces huge numbers, and the result sequence may contain erroneous output due to overflow (see the highlighted elements in the sample output above.)

Sample script

A sample script to demonstrate this select statement using xSQL can be run from the samples/xsql/scripts/financial directory with the following command:

     
    g 10