Running (cumultaive) statistics

Below query calculates running sum and running average of book sales, along with a cumulative data items.

the query cross-joins two instaces of table titles, grouping the result by the first-table(t1) title IDs and limiting the second table(tw) rows to ID values smaller than or equal to the t1 row to which they're joined.

table: titles
t1.idt1.sales
t01566
t029566
t0325667
t0413001

After cross join (titles)t1 and (titles)t2
t1.idt1.salest2.idt2.sales
t01566t01566
t029566t01566
t029566t029566
t0325667t01566
t0325667t029566
t0325667t0325667
t0413001t01566
t0413001t029566
t0413001t0325667
t0413001t0413001

Query:
SELECT
t1.ID,sum(t2.sales),avg(t2.sales),count(t2.sales)
FROM titles t1,titiles t2
WHERE t1.sales >= t2.sales
GROUP BY t1.ID


Result:




IDSUM(T2.SALES)AVG(T2.SALES)COUNT(T2.SALES)
15665661
21013250662
348800122004
42313377113

No comments:

Post a Comment