「MySQL基础」MySQL 统计最近30天的数据

74 阅读1分钟

🙏废话不多说系列,直接开整🙏

前提

(1)实现思路
  • 通过MySQL数据库自身生成一个虚拟表(只包含索引和天数集合);
  • 再将此表关联业务数据表的创建日期或者其他业务日期即可实现指定日期列表中需要统计的数据;
(2)注意事项

⚠注意:需要 root 权限,可以访问到 mysql 内置的 mysql数据库中的权限。

没有权限访问 mysql.help_topic 示例

image.png

有 权限访问 mysql.help_topic 示例

image.png

一、完整示例

(1)创建日期集合
-- 创建一个只包含 索引列、日期列 的临时表
SELECT
    @s := @s + 1 AS indexs,
    DATE_FORMAT( DATE( DATE_SUB( CURRENT_DATE, INTERVAL @s DAY ) ), '%Y-%m-%d' ) AS dates 
FROM
    mysql.help_topic, 
    ( SELECT @s := -1 ) temp  #不想包含当天,@s:=0
WHERE  @s < 5 -- 需要列举前N多少天
ORDER BY  dates 

结果如下:

image.png

(2)完整实例

业务:统计demo表中当前日期的前30天内每天新增的用户数。。

select
	date_table.dates as dateValue,
	IFNULL( temp.count, 0 ) as count
from
	(select
		@s := @s + 1 as indexs,
		DATE_FORMAT( DATE( DATE_SUB( 
            CURRENT_DATE, -- 1.指定日期当前日期(可修改 CURRENT_DATE → '2022-03-26' 的指定日期)
            -- '2022-03-26',
            interval @s day ) ), '%Y-%m-%d' ) as dates
	from mysql.help_topic,
		( select @s := 0 ) temp
	where @s < 30 -- 2.需要查询前N个日期
	order by dates
	) date_table
left join (select  
               left ( created_time, 10 ) as dateValue, 
               count(*) as count
           from demo t1 
           where 1 = 1 -- 3*.业务筛选逻辑写在此处
           group by left (created_time, 10) 
		) temp on date_table.dates = temp.dateValue
-- 4*.最后排序
order by date_table.dates desc;

实例结果:

image.png

🙏至此,非常感谢阅读🙏