【DB2】判断连续时间,如果间断则新增一条记录
需求描述
例如:产品A01 2017-01-02到2017-01-03产品状态都是差,那么就是一条记录 但是在2017-01-04这天的状态不是差,到了5日这天又是差了 就是另外一条记录了
需求处理
DROP TABLE tb; CREATE TABLE tb(product VARCHAR(100),dt TIMESTAMP,status VARCHAR(100)); INSERT INTO tb SELECT 'A01','2017-1-1','优秀' FROM SYSIBM.DUAL UNION ALL SELECT 'A01','2017-1-2','差' FROM SYSIBM.DUAL UNION ALL SELECT 'A01','2017-1-3','差' FROM SYSIBM.DUAL UNION ALL SELECT 'A01','2017-1-4','中等' FROM SYSIBM.DUAL UNION ALL SELECT 'A01','2017-1-5','差' FROM SYSIBM.DUAL UNION ALL SELECT 'A01','2017-1-6','中等' FROM SYSIBM.DUAL UNION ALL SELECT 'A02','2017-1-6','中等' FROM SYSIBM.DUAL UNION ALL SELECT 'A02','2017-1-7','差' FROM SYSIBM.DUAL UNION ALL SELECT 'A03','2017-1-6','差' FROM SYSIBM.DUAL UNION ALL SELECT 'A03','2017-1-7','差' FROM SYSIBM.DUAL UNION ALL SELECT 'A03','2017-1-9','差' FROM SYSIBM.DUAL ------- SELECT PRODUCT,MIN(DT) AS START_DT,MAX(DT) AS END_DATE FROM (SELECT A.*,ROW_NUMBER() OVER(ORDER BY PRODUCT,DT) RN FROM tb A WHERE status='差') GROUP BY PRODUCT,DAYS(DT)-RN ORDER BY PRODUCT
作者:奔跑的金鱼
声明:书写博客不易,转载请注明出处,请支持原创,侵权将追究法律责任
个性签名:人的一切的痛苦,本质上都是对自己无能的愤怒
如果觉得这篇文章对你有小小的帮助的话,记得在右下角点个“推荐”哦,博主在此感谢!