24.6. Summation of a Series

While this topic is a bit more mathematical than most SQL programmers actually have to use in their work, it does demonstrate the power of SQL and a little knowledge of some basic college math.

The summation of a series builds a running total of the values in a table and shows the cumulative total for each value in the series. Let’s create a table and some sample data.

CREATE TABLE Series
(seq_nbr INTEGER NOT NULL PRIMARY KEY,
val INTEGER NOT NULL,
answer INTEGER  -- null means not computed yet
);

 Sequences
 seq_nbr     val  answer
 =======================
   1          6       6
   2         41      47
   3         12      59
   4         51     110
   5         21     131
   6         70     201
   7         79     280
   8         62     342
   ...

This simple summation is not a problem.

UPDATE Series SET answer = (SELECT SUM(R1.val) FROM Series ...

Get Joe Celko's SQL for Smarties, 3rd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.