0

我需要帮助来优化我的 SQL 请求。

我有一个看起来像这样的表:

id,resgier_date,action
1,'2011-01-01 04:28:21','signup'
2,'2011-01-05 04:28:21','signup'
3,'2011-02-02 04:28:21','signup'

我如何选择和分组这些,所以输出是:

year,month,total,cumulative_sum
2011,1,2,2
2011,2,1,3

我想,通过一个请求,添加一列累积计数(id)。

我尝试这样的请求:

SELECT YEAR(REGISTER_DATE),
     count( * ),
     @running_total := @running_total + count( * ) AS cumulative_sum
FROM MYTABLE t
     JOIN (SELECT @running_total := 0) r
GROUP BY YEAR(REGISTER_DATE)
LIMIT 0 , 30

没有成功

谢谢你的帮助

4

1 回答 1

2

尝试

SELECT year, 
       month, 
       total, 
       @rt := @rt + total cumulative_sum
  FROM (
        SELECT YEAR(register_date) year,
               MONTH(register_date) month,
               COUNT(*) total
          FROM mytable
          GROUP BY YEAR(register_date), MONTH(register_date)
          LIMIT 0, 30
       ) n, (SELECT @rt := 0) r

输出

| YEAR | MONTH | TOTAL | CUMULATIVE_SUM |
-----------------------------------------
| 2011 |     1 |     2 |              2 |
| 2011 |     2 |     1 |              3 |

SQLFiddle

于 2013-03-13T07:55:27.390 回答