问题描述
|
我有一个如下表:
MysqL> select * from tries;
+----+--------+-----------+
| id | person | succeeded |
+----+--------+-----------+
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 2 | 0 |
| 4 | 4 | 1 |
| 5 | 2 | 1 |
| 6 | 2 | 0 |
| 7 | 3 | 0 |
| 8 | 3 | 0 |
| 9 | 3 | 0 |
| 10 | 1 | 0 |
| 11 | 4 | 1 |
| 12 | 4 | 1 |
+----+--------+-----------+
我希望那些(至少)有一个try
成功的人,紧接着是一个Failed1ѭ失败的人(分别由1
和0
给予)。当我说“跟随”时,是指同一个人的上一次尝试,并以较低的ѭ5给出。
因此,在这种情况下:
人2的成功尝试是id = 5
,失败的是id = 3
,因此符合条件。
人1没有立即跟随失败的成功,因此未能通过标准
人3没有成功,因此不符合条件
人4没有失败,因此未通过条件
我将如何编写这样的查询?
解决方法
SELECT t1.person,MIN(t1.id) as SuccessID
FROM tries t1
WHERE t1.succeeded = 1
AND t1.person IN (SELECT t2.person
FROM tries t2
WHERE t2.succeeded = 0
AND t2.id < t1.id)
GROUP BY t1.person
,Select ...
From tries As T
Join tries As T2
On T2.id = T.id + 1
And T2.succeeded = 0
Where T.succeeded = 1
如果我们不能认为Ids是完全连续的:
Select ...
From tries As T
Join (
Select T1.id,Min(T2.Id) As NextId
From tries As T1
Join tries As T2
On T2.id > T.id
Group By T1.id
) As TriesAndNext
On TriesAndNext.Id = T.Id
Join tries As TNext
On TNext.Id = TriesAndNext.NextId
And TNext.succeeded = 0
Where T.succeeded = 1