获取之前基于行的值

时间:2017-02-28 17:20:52

标签: mysql sql

这是我的表

+-----+-----+
| A   | B   |
+-----+-----+
|  1  | 300 |
|  2  | 300 |
|  3  | 0   |
|  4  | 0   |
|  5  | 100 |
|  6  | 100 |
|  7  | 100 |
|  8  | 100 |
|  9  | 0   |
| 10  | 0   |
+-----+-----+

给定一个值,让我们说100,我需要得到这个值的第一行,其中前一行等于0(按增加A的顺序)。

输出结果为:

+-----+-----+
|  A  |  B  |
+-----+-----+
|  5  | 100 |
+-----+-----+

2 个答案:

答案 0 :(得分:1)

数据库表是一组无序的行。当你说"第一行"和"排在"之前,我假设你的意思是增加A

的顺序

您可以使用用户变量执行此操作:

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;

Demo

答案 1 :(得分:1)

INNER JOIN本身怎么样。

<强>输入

// 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 |
+-----+-----+

<强>查询

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

<强>输出

// As requested in the demo.

+-----+-----+
|  A  |  B  |
+-----+-----+
|   5 | 100 |
|  13 | 100 |
|  20 | 100 |
+-----+-----+