- 创建员工登记表
CREATE TABLE `employee` (
`employee_no` varchar(10) NOT NULL COMMENT '员工编号',
`department` varchar(10) DEFAULT NULL COMMENT '部门',
`name` varchar(20) DEFAULT NULL COMMENT '员工姓名',
`create_time` datetime DEFAULT NULL COMMENT '创建时间',
PRIMARY KEY (`employee_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
- 插入若干条数据
INSERT INTO `employee` (`employee_no`, `department`, `name`, `create_time`) VALUES ('NO.001', '部门一', '李继阳', '2019-04-01 11:30:39');
INSERT INTO `employee` (`employee_no`, `department`, `name`, `create_time`) VALUES ('NO.002', '部门二', '邱立东', '2019-04-01 11:32:34');
INSERT INTO `employee` (`employee_no`, `department`, `name`, `create_time`) VALUES ('NO.003', '部门一', '孙永霞', '2019-05-01 11:33:00');
INSERT INTO `employee` (`employee_no`, `department`, `name`, `create_time`) VALUES ('NO.004', '部门一', '鲁明方', '2019-05-01 17:19:34');
INSERT INTO `employee` (`employee_no`, `department`, `name`, `create_time`) VALUES ('NO.005', '部门二', '朱华云', '2019-05-01 13:20:35');
INSERT INTO `employee` (`employee_no`, `department`, `name`, `create_time`) VALUES ('NO.006', '部门一', '李子天', '2019-06-07 13:28:27');
INSERT INTO `employee` (`employee_no`, `department`, `name`, `create_time`) VALUES ('NO.007', '部门一', '张萌', '2019-06-27 10:29:42');
INSERT INTO `employee` (`employee_no`, `department`, `name`, `create_time`) VALUES ('NO.008', '部门一', '赵龙', '2019-08-01 13:31:56');
INSERT INTO `employee` (`employee_no`, `department`, `name`, `create_time`) VALUES ('NO.009', '部门二', '方丽琼', '2019-08-01 08:32:44');
插入数据完成后,执行select * from employee
可以看到员工表数据如下
- 统计每个部门4月份和5月份分别有多少员工登记,查询
sql
如下
select department
,sum(
case when create_time >= '2019-04-01 00:00:00'
and create_time < '2019-05-01 00:00:00'
then 1 else 0 end
) as '4月'
,sum(
case when create_time >= '2019-05-01 00:00:00'
and create_time < '2019-06-01 00:00:00'
then 1 else 0 end
) as '5月'
from employee
group by department;
执行sql
可以看到结果如下
2. 统计每天有多少员工登记并汇总,sql
如下
select IFNULL(create_date,'合计') as create_date
,total
from (select
SUBSTRING(create_time , 1,10) as create_date
,count(*) as total
from employee
group by create_date
with rollup
) T;
其中,with rollup
的作用是对每天的员工登记数量进行列汇总
执行sql
可以看到结果如下