Here is my table
+-----+-----+
| A | B |
+-----+-----+
| 1 | 300 |
| 2 | 300 |
| 3 | 0 |
| 4 | 0 |
| 5 | 100 |
| 6 | 100 |
| 7 | 100 |
| 8 | 100 |
| 9 | 0 |
| 10 | 0 |
+-----+-----+
Given a value let's say 100, I need to get the first row of this value where the row before is equal to 0 (in the order of increasing A).
The output would be :
+-----+-----+
| A | B |
+-----+-----+
| 5 | 100 |
+-----+-----+
A database table is an unordered set of rows. When you say "first row" and "row before", I assume that you mean in the order of increasing A
You can use user variable to do this:
set @val := 100; -- to be searched
set @pre := -999999999;
select a, b
from (
select
t.*,
if(
@val = b and @pre = 0, -- if the required value is found and last value was 0
if(@pre := b, 1, 1), -- then 1
if(@pre := b, 0, 0) -- else 0
) flag
from t
order by A
) t where flag = 1;
How about an INNER JOIN
on itself.
Input
// From the demo provided in comments.
+-----+-----+
| A | B |
+-----+-----+
| 1 | 300 |
| 2 | 300 |
| 3 | 0 |
| 4 | 0 |
| 5 | 100 |
| 6 | 100 |
| 7 | 100 |
| 8 | 100 |
| 9 | 0 |
| 10 | 0 |
| 11 | 0 |
| 12 | 0 |
| 13 | 100 |
| 14 | 100 |
| 15 | 100 |
| 16 | 0 |
| 17 | 0 |
| 18 | 0 |
| 19 | 0 |
| 20 | 100 |
| 20 | 100 |
| 20 | 100 |
| 21 | 100 |
| 24 | 0 |
+-----+-----+
Query
SELECT yt1.A, MIN(yt1.B) AS B
FROM YourTable yt1
INNER JOIN YourTable yt2 ON yt2.A = yt1.A - 1
WHERE yt1.B = 100 AND yt2.B = 0
GROUP BY yt1.A
Output
// As requested in the demo.
+-----+-----+
| A | B |
+-----+-----+
| 5 | 100 |
| 13 | 100 |
| 20 | 100 |
+-----+-----+
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.