MySQL滚动行数

时间:2018-09-06 08:20:55

标签: mysql sql database

我正在尝试统计学生网站上的注册增长情况。

查询如下:

SELECT COUNT(type) as student_count, MONTH(created_at) as month, YEAR(created_at) as year
FROM users
WHERE type = 'student'
GROUP BY MONTH(created_at), YEAR(created_at)
ORDER BY year, month

这将产生以下输出: enter image description here

我要在查询中实现的目标是继续将前几行中的student_counts加起来。

所以:

2014年12月应该有15名学生

2015年1月应该有16名学生

2015年2月应该有34名学生

以此类推...

在SQL中这是否可行?还是在代码本身中输出数据时更好地做到这一点?

4 个答案:

答案 0 :(得分:1)

select *, @sum := @sum + student_count as sum
from
(
    SELECT YEAR(created_at) as year, 
           MONTH(created_at) as month, 
           COUNT(type) as student_count
    FROM users
    WHERE type = 'student'
    GROUP BY year, month
    ORDER BY year, month
) tmp
CROSS JOIN (select @sum := 0) s

答案 1 :(得分:0)

尝试使用汇总

SELECT COUNT(type) as student_count, MONTH(created_at) as month, YEAR(created_at) as year
FROM users
WHERE type = 'student'
GROUP BY YEAR(created_at), MONTH(created_at) WITH ROLLUP 

答案 2 :(得分:0)

在MySQL中处理此问题的一种方法是使用相关的子查询来查找正在运行的总数。

SELECT DISTINCT
    (SELECT COUNT(*) FROM users u2
     WHERE DATE_FORMAT(u2.created_at, '%Y-%m') <=
           DATE_FORMAT(u1.created_at, '%Y-%m')) AS student_count,
    DATE_FORMAT(created_at, '%Y-%m') AS ym
FROM users u1
WHERE type = 'student'
ORDER BY DATE_FORMAT(created_at, '%Y-%m');

Demo

这里没有什么要解释的,除了SELECT DISTINCT将表中每个唯一的年月值作为单个记录提供给我们。然后,我们计算该时间点或更早的所有行,以找到运行总计。

答案 3 :(得分:0)

尝试一下:

SELECT @cumulative := 0;
SELECT @cumulative := @cumulative + student_count student_count,
       month, year
FROM (
    SELECT COUNT(type) as student_count,
           MONTH(created_at) as month,
           YEAR(created_at) as year
    FROM users
    WHERE type = 'student'
    GROUP BY MONTH(created_at), YEAR(created_at)
) A ORDER BY year, month