MySQL按天分组统计,⽆数据显⽰0
问题描述:
按照天数统计每天的总数,如果其中有⼏天没有数据,那么group by 返回会忽略那⼏天,不符合报表统计的需求。当天没有数据的话该如何填充0 ?
数据库脚本
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for employee
-- ----------------------------
DROP TABLE IF EXISTS `employee`;
CREATE TABLE `employee`  (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`age` int(11) NULL DEFAULT NULL,
`sex` char(2) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`addr` varchar(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT NULL,
`create_time` datetime(0) NULL DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 9 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_unicode_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-
- Records of employee
-- ----------------------------
INSERT INTO `employee` VALUES (1, 'zhansan', 18, '男', '北京市', '2019-06-13 18:41:34');
INSERT INTO `employee` VALUES (2, 'lisi', 20, '男', '天津市', '2019-06-14 18:41:43');
INSERT INTO `employee` VALUES (3, 'wangwu', 28, '男', '上海', '2019-06-18 18:41:37');
INSERT INTO `employee` VALUES (4, 'lisi', 35, '男', '⾹港', '2019-06-18 18:41:51');
INSERT INTO `employee` VALUES (5, 'limei', 22, '⼥', '⼭西', '2019-06-19 18:41:58');
INSERT INTO `employee` VALUES (6, 'liting', 26, '⼥', '北京市', '2019-06-21 18:42:03');
INSERT INTO `employee` VALUES (7, 'wangdan', 31, '⼥', '河北省', '2019-06-19 19:22:31');
INSERT INTO `employee` VALUES (8, 'limeili', 19, '⼥', '安徽省', '2019-06-19 19:27:45');groupby分组
SET FOREIGN_KEY_CHECKS = 1;
先看解决⽅案:
/**
如果使⽤当前⽇期的话,将'2019-06-22'替换为CURDATE( )
*/
SELECT
t1.`day`,
COUNT( t2.id ) num
FROM
(
SELECT
@cdate := DATE_ADD( @cdate, INTERVAL - 1 DAY ) DAY
FROM
( SELECT @cdate := DATE_ADD( '2019-06-22', INTERVAL + 1 DAY ) FROM employee ) t0
LIMIT 7
) t1
LEFT JOIN (
SELECT
DATE( a.create_time ) DAY,
a.id
FROM
employee a
WHERE
DATE( create_time ) <= '2019-06-22' AND DATE( create_time ) > DATE_SUB( '2019-06-22', INTERVAL 7 DAY )
) t2 ON t2.DAY = t1.DAY
GROUP BY
t1.`day`;
执⾏数据结果完全符合需求;
连续⽇期mysql
/**
如果指定开始⽇期的话,将CURDATE( )替换为'2019-06-13'
*/
SELECT
@cdate := DATE_ADD( @cdate, INTERVAL - 1 DAY ) DAY
FROM
( SELECT @cdate := DATE_ADD( CURDATE( ), INTERVAL + 1 DAY ) FROM employee ) t0
LIMIT 7;
SQL分析:
1. @cdate :=  是定义名为cdate的变量并赋值(select 后⾯必须⽤:=)
2. @cdate := DATE_ADD(CURDATE(), INTERVAL + 1 DAY) 按照当前⽇期,加⼀天
3. SELECT @cdate := DATE_ADD(CURDATE(), INTERVAL + 1 DAY) FROM 数据库表名
4. @cdate := DATE_ADD(@cdate, INTERVAL - 1 DAY) DAY  把定义的cdate变量天数-1(⾃减)
5. LIMIT 7 限制⼀下条数,得到了指定⽇期往前7天的记录
6. left join group by t1.day 即按照左表关联业务数据,根据左表的⽇期分组,即分成了指定的7天数据,有记录就统计条数,没有记录就是0

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。