1、建表
DROP TABLE IF EXISTS `performance`; CREATE TABLE `performance` ( `id` int(11) NOT NULL, `city` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL, `amout` decimal(10, 2) NULL DEFAULT NULL, `time` datetime(0) NULL DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
2、SQL按时间
-- 按年 -- 第一种 SELECT DATE_FORMAT( time, '%Y' ) years, sum( amout ) amout FROM performance GROUP BY years ORDER BY years ASC; -- 第二种 SELECT YEAR ( time ) years, sum( amout ) amout FROM performance GROUP BY years ORDER BY years ASC; -- 按季度 -- 第一种 SELECT CONCAT( YEAR ( time ), '年-第', FLOOR(( date_format( time, '%m' )+ 2 )/ 3 ), '季度' ) quarters, sum( amout ) amout FROM performance GROUP BY quarters ORDER BY quarters -- 第二种 SELECT CONCAT( YEAR ( time ), '年-第', QUARTER ( time ), '季度') quarters, sum( amout ) amout FROM performance GROUP BY quarters order by quarters -- 按月 -- 第一种 SELECT DATE_FORMAT( time, '%Y-%m' ) months, sum( amout ) amout FROM performance GROUP BY months ORDER BY months ASC; -- 第二种 SELECT CONCAT( YEAR ( time ), '-', MONTH ( time )) months, sum( amout ) amout FROM performance GROUP BY months ORDER BY months ASC; -- 按周 -- 第一种 SELECT DATE_FORMAT( time, '%x年-第%v周' ) weeks, sum( amout ) amout FROM performance GROUP BY weeks ORDER BY weeks ASC; -- 第二种 SELECT CONCAT( YEAR ( time ), '-', WEEK ( time ) + 1) weeks, sum( amout ) amout FROM performance GROUP BY weeks ORDER BY weeks ASC;
-- 按日 SELECT DATE_FORMAT( time, '%Y-%m-%d' ) days, sum( amout ) amout FROM performance GROUP BY days ORDER BY days ASC;
3、分城市按月查询
-- 每个城市按月 SELECT city, DATE_FORMAT( time, '%Y-%m' ) months, sum( amout ) amout FROM performance GROUP BY city, months ORDER BY months ASC;