可以使用以下 SQL 语句来统计近7天的数据量,并按时间戳分组。如果某一天没有数据,则将其填充为0。
SELECT
DATE_FORMAT(FROM_UNIXTIME(`timestamp`), '%Y-%m-%d') AS date,
COUNT(*) AS count
FROM
`table_name`
WHERE
`timestamp` >= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 7 DAY))
GROUP BY
date
ORDER BY
`timestamp` ASC;
解释说明:
DATE_FORMAT(FROM_UNIXTIME(
timestamp), '%Y-%m-%d') AS date
将时间戳转换为日期格式,例如 2021-03-01。COUNT(*) AS count
统计每天数据的数量。WHERE
timestamp>= UNIX_TIMESTAMP(DATE_SUB(CURDATE(), INTERVAL 7 DAY))
指定查询最近7天的数据。GROUP BY date
按日期分组。ORDER BY
timestampASC
按照从小到大的顺序排序。
查询结果示例: