How to update MySQL table with a cumulative count of events with the same date

Posted by John on Stack Overflow See other posts from Stack Overflow or by John
Published on 2012-06-20T02:02:25Z Indexed on 2012/06/20 3:16 UTC
Read the original article Hit count: 166

Filed under:

I have a table which I pull data from. This data has a date and a stock symbol. There can be multiple rows of data with the same date and different stock symbols. I need to update the table so that there is a running total for all rows with the same date. When a new date occurs the cumulative count re-sets to 1 and then resumes.

A typical query:

mysql> SELECT Sym 'sym' ,  fdate as 'FilledDate',  TsTradeNum 'numT'
-> FROM trades_entered_b2
-> WHERE fDate >= '2009-08-03' AND fDate <= '2009-08-07'
-> LIMIT 10;


+------+------------+------+
| sym  | FilledDate | numT |
+------+------------+------+
| WAT   | 2009-08-03 |    0 |
| ALGN  | 2009-08-04 |    0 |
| POT   | 2009-08-05 |    0 |
| PTR   | 2009-08-06 |    0 |
| SCHW  | 2009-08-06 |    0 |
| FDO   | 2009-08-07 |    0 |
| NBL   | 2009-08-07 |    0 |
| RRC   | 2009-08-07 |    0 |
| WAT   | 2009-08-08 |    0 |
| COCO  | 2009-08-08 |    0 |
+------+------------+------+

What I want:

+------+------------+------+
| sym  | FilledDate | numT |
+------+------------+------+
| WAT   | 2009-08-03 |    1 |
| ALGN  | 2009-08-04 |    1 |
| POT   | 2009-08-05 |    1 |
| PTR   | 2009-08-06 |    1 |
| SCHW  | 2009-08-06 |    2 |
| FDO   | 2009-08-07 |    3 |
| NBL   | 2009-08-07 |    4 |
| RRC   | 2009-08-07 |    5 |
| WAT   | 2009-08-08 |    1 |
| COCO  | 2009-08-08 |    2 |
+------+------------+------+

What I need to do is update the TsTradeNum column with the correct values. I have tried to create a function and various queries all failed.

Any ideas? Thanks in advance

© Stack Overflow or respective owner

Related posts about mysql