Sum up values in SQL once all values are available

Posted by James Brown on Stack Overflow See other posts from Stack Overflow or by James Brown
Published on 2012-12-04T10:58:40Z Indexed on 2012/12/04 11:05 UTC
Read the original article Hit count: 185

Filed under:
|

I have events flowing into a MySQL database and I need to group and sum the events to transactions and store away into another table. The data looks like:

+----+---------+------+-------+
| id | transid | code | value |
+----+---------+------+-------+
|  1 |       1 | b    |    12 |
|  2 |       1 | i    |    23 |
|  3 |       2 | b    |    34 |
|  4 |       1 | e    |    45 |
|  5 |       3 | b    |    56 |
|  6 |       2 | i    |    67 |
|  7 |       2 | e    |    78 |
|  8 |       3 | i    |    89 |
|  9 |       3 | i    |    90 |
+----+---------+------+-------+

The events arrive in batches and I would like to create the transaction by summing up the values for each transid, like:

select transid, sum(value) from eventtable group by transid;

but only after all the events for that transid have arrived. That is determined by the event with the code e (b for the beginning, e for the end and i for varying amount of intermediates). Being a novice in SQL, how could I implement the requirement for the existance of the end code before the summing?

© Stack Overflow or respective owner

Related posts about mysql

Related posts about sql