I have this table
ID value user stock ----|--------|---------|--------- 1 | 10 | mark | AAPL 2 | 20 | rob | GOOG 3 | 30 | mark | AAPL 4 | -40 | mark | AAPL 5 | -10 | rob | GOOG 6 | 25 | mark | GOOG 7 | 5 | mark | GOOG 8 | 45 | mark | AAPL
I would like to build a query (possibly without using any PGSQL function) that returns the rows shown below. It should start in order (ID ASC) summing "value" column grouped by user,stock. If the temporary sum is 0, all the previous rows (for that group) will be discarded.
id value user stock ----|--------|---------|--------- 2 | 20 | rob | GOOG 5 | -10 | rob | GOOG 6 | 25 | mark | GOOG 7 | 5 | mark | GOOG 8 | 45 | mark | AAPL
I think that OVER (PARTITION BY) and WINDOW function should be used
SELECT *, SUM(value) OVER w AS scm
FROM "mytable"
WINDOW w AS (PARTITION BY user,stock ORDER BY id ASC)
this returns next table
ID value user stock scm ----|--------|---------|---------|------- 1 | 10 | mark | AAPL | 10 2 | 20 | rob | GOOG | 20 3 | 30 | mark | AAPL | 40 4 | -40 | mark | AAPL | 0 5 | -10 | rob | GOOG | 10 6 | 25 | mark | GOOG | 25 7 | 5 | mark | GOOG | 30 8 | 45 | mark | AAPL | 45
So this should be a good starting point, because it shows that APPL for mark is 0 (id=4) and for that group (AAPL,mark) I should keep all the following rows. The rule is: for each group (stock,user) keep all the rows following the last row with scm=0