MySql 查询 运行 总计 return 每年的值相同

MySql Query for running totals return same value for each years

我不是 MySql 方面的专家,我想做的是,创建一个查询 returns 运行 按月和年的总计:

SELECT DISTINCT
    date_format(t.created_at, "%M") AS month,
    date_format(t.created_at, "%Y") AS year,
    SUM(COUNT(*)) over (order by MONTH(created_at) ) as cumulative
FROM team t
GROUP BY YEAR(created_at), MONTH(created_at)
ORDER BY  MONTH(created_at) ASC

查询结果: enter image description here

有人知道怎么解决吗? :(

你不能使用聚合函数容器聚合函数,所以你可以尝试使用子查询get count 为每个年,月,然后在主查询中使用window 函数

SELECT  month,
        year,
        SUM(cnt) over (order by year,month) cumulative
FROM (
    SELECT MONTH(created_at) AS month,
        YEAR(created_at) AS year,
        COUNT(*) as cnt
    FROM team t
    GROUP BY YEAR(created_at), MONTH(created_at)
) t1