1. 创建表
CREATE TABLE `sales` ( `id` int(11) NOT NULL AUTO_INCREMENT, `date` date NOT NULL, `amount` double NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
2. 插入数据
INSERT INTO `sales` (`date`, `amount`) VALUES ('2021-01-01', 100), ('2021-01-02', 200), ('2021-01-02', 150), ('2021-01-03', 300), ('2021-01-03', 250), ('2021-01-03', 200), ('2021-01-04', 400);
3. 按日期统计
SELECT `date`, SUM(`amount`) FROM `sales` GROUP BY `date`;
输出结果为:
+------------+-------------+ | date , SUM(amount), +------------+-------------+ | 2021-01-01, 100 , | 2021-01-02, 350 , | 2021-01-03, 750 , | 2021-01-04, 400 , +------------+-------------+
4. 按周统计
SELECT YEARWEEK(`date`) AS `week`, SUM(`amount`) FROM `sales` GROUP BY YEARWEEK(`date`);
输出结果为:
+------+-------------+ | week, SUM(amount), +------+-------------+ | 20201, 450 , | 20202, 750 , +------+-------------+
5. 按月统计
SELECT DATE_FORMAT(`date`, '%Y-%m') AS `month`, SUM(`amount`) FROM `sales` GROUP BY DATE_FORMAT(`date`, '%Y-%m');
输出结果为:
+---------+-------------+ | month , SUM(amount), +---------+-------------+ | 2021-01, 1600 , +---------+-------------+
通过以上的几个例子,大家可以看到使用MySQL按时间统计数据是非常方便的。无论是按天、周、月或者其他时间维度,都可以通过简单的SQL语句来实现。因此,在实际的数据分析和报告中,按时间统计数据的功能非常重要。