mysql滚动行数

dsf9zpds  于 2021-06-20  发布在  Mysql
关注(0)|答案(4)|浏览(357)

我想对一个学生网站的注册人数进行滚动统计。
查询如下所示:

  1. SELECT COUNT(type) as student_count, MONTH(created_at) as month, YEAR(created_at) as year
  2. FROM users
  3. WHERE type = 'student'
  4. GROUP BY MONTH(created_at), YEAR(created_at)
  5. ORDER BY year, month

这将产生以下输出:

我试图在查询中实现的是不断地将 student_counts 从上一行。
所以:
2014年12月应该有15名学生
2015年1月应该有16名学生
2015年2月应该有34名学生
等等。。。
这在sql中是可能的还是在输出代码本身中的数据时这样做更好?

bjg7j2ky

bjg7j2ky1#

  1. select *, @sum := @sum + student_count as sum
  2. from
  3. (
  4. SELECT YEAR(created_at) as year,
  5. MONTH(created_at) as month,
  6. COUNT(type) as student_count
  7. FROM users
  8. WHERE type = 'student'
  9. GROUP BY year, month
  10. ORDER BY year, month
  11. ) tmp
  12. CROSS JOIN (select @sum := 0) s
tsm1rwdh

tsm1rwdh2#

尝试与汇总一起使用

  1. SELECT COUNT(type) as student_count, MONTH(created_at) as month, YEAR(created_at) as year
  2. FROM users
  3. WHERE type = 'student'
  4. GROUP BY YEAR(created_at), MONTH(created_at) WITH ROLLUP
anauzrmj

anauzrmj3#

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

  1. SELECT DISTINCT
  2. (SELECT COUNT(*) FROM users u2
  3. WHERE DATE_FORMAT(u2.created_at, '%Y-%m') <=
  4. DATE_FORMAT(u1.created_at, '%Y-%m')) AS student_count,
  5. DATE_FORMAT(created_at, '%Y-%m') AS ym
  6. FROM users u1
  7. WHERE type = 'student'
  8. ORDER BY DATE_FORMAT(created_at, '%Y-%m');

演示

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

ha5z0ras

ha5z0ras4#

试试这个:

  1. SELECT @cumulative := 0;
  2. SELECT @cumulative := @cumulative + student_count student_count,
  3. month, year
  4. FROM (
  5. SELECT COUNT(type) as student_count,
  6. MONTH(created_at) as month,
  7. YEAR(created_at) as year
  8. FROM users
  9. WHERE type = 'student'
  10. GROUP BY MONTH(created_at), YEAR(created_at)
  11. ) A ORDER BY year, month

相关问题