代码之家  ›  专栏  ›  技术社区  ›  Marcus Christiansen

MySQL滚动行数

  •  2
  • Marcus Christiansen  · 技术社区  · 6 年前

    我想对一个学生网站的注册人数进行滚动统计。

    查询如下所示:

    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年2月应该有34名学生

    等等。。。

    这在SQL中是可能的还是在输出代码本身中的数据时这样做更好?

    4 回复  |  直到 6 年前
        1
  •  1
  •   juergen d    6 年前
    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
    
        2
  •  0
  •   ScaisEdge    6 年前

    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 
    
        3
  •  0
  •   Michał Turczyn    6 年前

    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
    
        4
  •  0
  •   Tim Biegeleisen    6 年前

    在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 将表中每个唯一的年-月值作为单个记录提供给我们。然后,我们对该时间点或更早时间点的所有行进行计数,以找到运行总数。