1

我有一张表,我从中提取数据。该数据具有日期和股票代码。可以有多行具有相同日期和不同股票代码的数据。我需要更新表格,以便所有具有相同日期的行都有一个运行总计。当一个新的日期出现时,累积计数重新设置为 1,然后恢复。

一个典型的查询:

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 |
+------+------------+------+

我想要的是:

+------+------------+------+
| 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 |
+------+------------+------+

我需要做的是用正确的值更新 TsTradeNum 列。我试图创建一个函数,但各种查询都失败了。

有任何想法吗?提前致谢

4

1 回答 1

0

可以在下面尝试。如果前一行日期与当前行相同,则查询会将 numT 递增 1,否则它将 numT 重置为 1。

SELECT sym, FilledDate, numT  
FROM(
SELECT sym, FilledDate,
   @count:=CASE WHEN ( @date <> FilledDate) THEN 1 
                ELSE 
                    @count+1                     
                END AS numT,
    @date:=FilledDate as dlset        
FROM
(SELECT @count:= -1) s,
(SELECT @date:= -1) d,    
  (SELECT id, sym, FilledDate
   FROM mytable3  
   ORDER BY FilledDate,sym desc        
  ) t ) a 
于 2012-06-20T03:13:19.097 回答