sql小练习,连续次数
数据样例:
小鹏汽车充电有两种类型,快充、慢充,有如下数据:
车辆 ID 充电时间 充电类型
其中 1 为快充,0 为慢充,求每辆车最长 连续快充次数 ,以上例子结果为
a 3
b 0
请写出对应的 SQL
SELECT b.id , IFNULL(MAX(times),0) as '最长' from ( SELECT id FROM `xiaopengcar` GROUP BY id ) b LEFT JOIN (SELECT id, count(id) as times from (SELECT id, LEFT(date,10) as dsa, type, ROW_NUMBER()OVER(ORDER BY LEFT(date,10) ASC ) as num1 FROM `xiaopengcar`) a WHERE type = '1' GROUP BY id , DATE_ADD(dsa,INTERVAL-num1 day)) c on b.id = c.id GROUP BY b.id