我需要帮助来优化我的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
没有成功
谢谢(给你帮助
答案 0 :(得分: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 强>