查询出银行柜员半小时内办理开户业务的记录。看看是否存在半个小时内办理了3笔及以上的开户业务。
给出了一张表,里面是一个柜员的操作记录,表records的结构为:
字段 | 数据类型 |
---|---|
Cid(客户id) | int |
Ctime(时间) | datetime |
方法一:用窗口函数(需要MySQL8.0以上版本);
方法二:常规的方法。
本案例采用了方法二。由于MySQL8.0版本安装过程曲折,未能顺利安装成功。
1、在MySQL中创建数据库bank
CREATE DATABASE bank;
2、创建表records
CREATE TABLE records(
Cid varchar(10) NOT NULL,
Ctime datetime NOT NULL
);
3、插入数据
(拟插入20条记录)
INSERT INTO records VALUES('adsf', '2017-5-27 10:55:00');
INSERT INTO records VALUES('ngfd', '2017-5-27 10:56:00');
INSERT INTO records VALUES('brsd', '2017-5-27 11:12:33');
INSERT INTO records VALUES('afdg', '2017-5-27 11:30:00');
INSERT INTO records VALUES('4045', '2017-5-27 11:33:23');
INSERT INTO records VALUES('sdsa', '2017-5-27 11:41:21');
INSERT INTO records VALUES('bvrt', '2017-5-27 11:52:55');
INSERT INTO records VALUES('4275', '2017-5-27 12:00:03');
INSERT INTO records VALUES('2578', '2017-5-27 12:04:00');
INSERT INTO records VALUES('7869', '2017-5-27 12:15:00');
INSERT INTO records VALUES('2479', '2017-5-27 12:21:20');
INSERT INTO records VALUES('4537', '2017-5-27 12:28:00');
INSERT INTO records VALUES('wefi', '2017-5-27 12:37:24');
INSERT INTO records VALUES('jrty', '2017-5-27 12:44:00');
INSERT INTO records VALUES('sdfg', '2017-5-27 12:50:11');
INSERT INTO records VALUES('sdvf', '2017-5-27 12:55:25');
INSERT INTO records VALUES('afds', '2017-5-27 13:08:00');
INSERT INTO records VALUES('jhtg', '2017-5-27 13:12:00');
INSERT INTO records VALUES('7632', '2017-5-27 13:15:00');
INSERT INTO records VALUES('fghd', '2017-5-27 13:16:00');
4、自连接
将表中每一条记录,都与20条记录连接起来,得到400条记录(即20*20)。
SELECT a.*, b.*
FROM records a, records b
ORDER BY a.Ctime, b.Ctime;
5、求时间差,新增计算字段记录该时间差
SELECT a.Cid,
a.Ctime AS t1,
b.Cid,
b.Ctime AS t2,
(b.Ctime -a.Ctime) AS t1_t2
FROM records a, records b
ORDER BY a.Ctime, b.Ctime;
6、筛选出与原20条记录相隔半个小时内的所有记录
共有41条
SELECT a.Cid,
a.Ctime AS t1,
b.Cid,
b.Ctime AS t2,
(b.Ctime -a.Ctime) AS t1_t2
FROM records a, records b
WHERE (b.Ctime -a.Ctime) > 0 AND (b.Ctime - a.Ctime) <= 3000
ORDER BY a.Ctime, b.Ctime;
7、对这41条记录,分组计数
SELECT *
FROM (
SELECT a.Cid, count(*) as cnt
FROM (
SELECT a.Cid,
a.Ctime as t1,
b.Cid,
b.Ctime as t2,
(b.Ctime -a.Ctime) AS t1_t2
FROM records a, records b
WHERE (b.Ctime -a.Ctime) > 0 AND (b.Ctime -a.Ctime) <= 3000
ORDER BY a.Ctime, b.Ctime
) A
GROUP BY a.Cid
) B
ORDER BY B.cnt DESC;
8、其它
(1)时间差。
‘2017-5-27 12:44:00’与’2017-5-27 12:50:11’,相差6分11秒,在这里计算结果显示为611。故半个小时的判断条件为:0-3000,即:WHERE ( b.Ctime -a.Ctime ) > 0 AND ( b.Ctime -a.Ctime ) <= 3000
(2)查询是否存在一个小时内办理了5笔及以上的开户业务
SELECT *
FROM (
SELECT a.Cid, count(*) as cnt
FROM (
SELECT a.Cid,
a.Ctime as t1,
b.Cid,
b.Ctime as t2,
(b.Ctime -a.Ctime) AS t1_t2
FROM records a, records b
WHERE (b.Ctime -a.Ctime) > 0 AND (b.Ctime -a.Ctime) <= 10000
ORDER BY a.Ctime, b.Ctime
) A
GROUP BY a.Cid
) B
ORDER BY B.cnt DESC;
来源:CSDN
作者:chow28
链接:https://blog.csdn.net/chow28/article/details/104459770