统计用户初次领证后三年(非自然年)内,每年各级违法各有多少次。

考点:SUBSTR()、TIMESTAMPDIFF()

题目:统计用户初次领证后三年(非自然年)内,每年各级违法各有多少次。

题目

1.建表:

CREATE TABLE IF NOT EXISTS `illegal_1`(
   `id` INT UNSIGNED AUTO_INCREMENT,
   `user_id` INT NOT NULL,
   `cclzrq` DATE NOT NULL,
   PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `illegal_2`(
   `id` INT UNSIGNED AUTO_INCREMENT,
   `user_id` INT NOT NULL,
   `vio_level` VARCHAR(5) NOT NULL,
	 `vio_time` DATETIME NOT NULL,
   PRIMARY KEY ( `id` )
)ENGINE=InnoDB DEFAULT CHARSET=utf8;

2.插入数据:

insert into illegal_1 (user_id, cclzrq) values('10023','2015-04-21');
insert into illegal_1 (user_id, cclzrq) values('15674','1998-05-12');
insert into illegal_1 (user_id, cclzrq) values('45345','2008-03-19');
insert into illegal_1 (user_id, cclzrq) values('87945','2004-08-26');
insert into illegal_1 (user_id, cclzrq) values('12355','2018-06-08');

insert into illegal_2 (user_id, vio_level, vio_time) values('10023','一级', '2017-08-07 14:28:53');
insert into illegal_2 (user_id, vio_level, vio_time) values('15674','一级', '2015-04-13 12:25:52');
insert into illegal_2 (user_id, vio_level, vio_time) values('87945','三级', '2006-05-21 16:22:16');
insert into illegal_2 (user_id, vio_level, vio_time) values('45345','三级', '2010-05-21 16:22:16');
insert into illegal_2 (user_id, vio_level, vio_time) values('12355','二级', '2020-05-21 16:22:16');
insert into illegal_2 (user_id, vio_level, vio_time) values('12355','一级', '2020-05-20 16:22:16');
insert into illegal_2 (user_id, vio_level, vio_time) values('12355','一级', '2020-04-20 16:22:16');

3.查询数据:

SELECT t3.user_id as user_id, SUBSTR(t3.vio_time,1,4) as vio_year, t3.vio_level as vio_level, count(t3.user_id) as vio_num 
FROM(
	SELECT t1.user_id as user_id, t1.cclzrq as cclzrq, t2.vio_level as vio_level, t2.vio_time as vio_time
	FROM illegal_1 t1
	join illegal_2 t2
	ON t1.user_id = t2.user_id
	WHERE TIMESTAMPDIFF(year, t1.cclzrq, t2.vio_time) <= 3)t3
GROUP BY t3.user_id, SUBSTR(t3.vio_time,1,4), t3.vio_level
ORDER BY t3.user_id, SUBSTR(t3.vio_time,1,4), t3.vio_level
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值