题目链接:点击打开链接
题目大意:略。
解题思路:解决方案(2)代码看似多,但是思路很清晰,一步一步做下来;解决方案(1)变量 @id 中间虽然使用了 UNION ALL,但是还是会继续上面的数值接着来,而不是重新从 0 开始噢。
AC 代码
--解决方案(1) SELECTperiod_state, MIN(date) ASstart_date, MAX(date) ASend_dateFROM( SELECTfail_dateASdate, 'failed'ASperiod_state, IF(DATEDIFF( , :=fail_date) =-1, , :=+1) ASidFROMFaileda1, (SELECT :=0, :=NULL) b1UNIONALLSELECTsuccess_dateASdate, 'succeeded'ASperiod_state, IF(DATEDIFF( , :=success_date) =-1, , :=+1) ASidFROMSucceededa2, (SELECT :=0, :=NULL) b2) t3WHEREdateBETWEEN"2019-01-01"AND"2019-12-31"GROUPBYt3.idORDERBYstart_date--解决方案(2) WITHt1AS(SELECTCAST( :=+IF(ISNOTNULLANDDATEDIFF(success_date, ) =1, 0, 1) ASSIGNED) rk, :=success_datedt, 1markFROMSucceeded, (SELECT :=null, :=0) initWHEREsuccess_dateBETWEEN'2019-01-01'AND'2019-12-31'), t2AS(SELECTrs2.minndt1, rs1.maxndt2, rs1.rk, rs1.markFROM(SELECTMAX(dt) maxn, rk, markFROMt1GROUPBYrk) rs1JOIN(SELECTMIN(dt) minn, rk, markFROMt1GROUPBYrk) rs2ONrs1.rk=rs2.rk), t3AS(SELECTCAST( :=+IF(ISNOTNULLANDDATEDIFF(fail_date, ) =1, 0, 1) ASSIGNED) rk, :=fail_datedt, 0markFROMFailed, (SELECT :=null, :=0) initWHEREfail_dateBETWEEN'2019-01-01'AND'2019-12-31'), t4AS(SELECTrs2.minndt1, rs1.maxndt2, rs1.rk, rs1.markFROM(SELECTMAX(dt) maxn, rk, markFROMt3GROUPBYrk) rs1JOIN(SELECTMIN(dt) minn, rk, markFROMt3GROUPBYrk) rs2ONrs1.rk=rs2.rk) SELECTIF(mark=0, 'failed', 'succeeded') period_state, dt1start_date, dt2end_dateFROM (SELECT*FROMt2UNIONALLSELECT*FROMt4) RSORDERBYdt1