表:
id driver_id status
1 23 1
2 23 1
3 22 1
4 23 0
5 22 1
6 22 1
7 22 0
8 22 1
9 23 1
我想要一个select查询来检查driver_id状态为1,因此检查三次或更多次,总计数和ID
上表的结果应该是:
id driver_id status total_count
3 22 1 3
5 22 1 3
6 22 1 3
因为driver_id具有状态1三次而没有任何其他状态,如0,而不是23,因为在id 1和id 2处具有状态1并且在id 4处具有状态0所以总计数< 3。
这是我的原始表:
在此表中,我正在检查状态52
我必须取回取消行程的司机=>连续3次
答案 0 :(得分:4)
body {
padding-bottom: 15px;
@include background-image(linear-gradient(#c3c3c3, white 350px));
}
结果
/*
DROP TABLE T;
CREATE TABLE T(id INT,driver_id INT, status INT);
TRUNCATE TABLE T;
INSERT INTO T VALUES
(1, 23, 1),
(2, 23, 1),
(3, 22, 1),
(4, 23, 0),
(5, 22, 1),
(6, 22, 1),
(7, 22, 0),
(8, 22, 1),
(9, 23, 0);
*/
SELECT T.ID,T.DRIVER_ID,T.STATUS,S.RN Total_count FROM
(
SELECT U.BN,MAX(U.RN) RN FROM
(
SELECT T.*,
IF(CONCAT(T.DRIVER_ID,STATUS) = @PREV,@BN,@BN:=@BN+1) BN,
IF(CONCAT(T.DRIVER_ID,STATUS) <> @PREV,@RN:=1,@RN:=@RN+1) RN,
@PREV:=CONCAT(T.DRIVER_ID,STATUS) P
FROM (SELECT @RN:=0,@BN:=0,@PREV:='') RN, T
ORDER BY DRIVER_ID,ID
) U
WHERE U.RN >= 3
GROUP BY U.BN
) S
JOIN
(SELECT T.*,
IF(CONCAT(T.DRIVER_ID,STATUS) = @PREV1,@BN1,@BN1:=@BN1+1) BN,
IF(CONCAT(T.DRIVER_ID,STATUS) <> @PREV1,@RN1:=1,@RN1:=@RN1+1) RN,
@PREV1:=CONCAT(T.DRIVER_ID,STATUS) P
FROM (SELECT @RN1:=0,@BN1:=0,@PREV1:='') RN, T
ORDER BY DRIVER_ID,ID) T ON T.BN = S.BN
ORDER BY T.DRIVER_ID,T.ID