简体   繁体   English

以SQL查询形式循环

[英]Loop in a form of sql query

I don't know where to start so I will just post an example what I need: 我不知道从哪里开始,所以我只举一个我需要的例子:

A   B
5   0
10  0
15  0
20  0
25* 1*
30  0
35  1
40  1
45* 0
50  0
55  0
60  0
65  0
70  1
75  1
80  0
85  0

I need a query that will look for 1 in column B (first row found in 25 1),"entry point" from this point, go down and look for first column A, that is 20 more than a A in the start point - "exit point" (found row 45 0), return row index of "entry point" and "exit point" , in this case 25 1 and 45 0 rows. 我需要一个查询,该查询将在B列中查找1(在25 1中找到第一行),从这一点开始查找“入口点”,然后向下查找第一列A,即在起始点处比A多20 “出口点”(找到第45 0行),返回“入口点”和“出口点”的行索引,在这种情况下为25 1和45 0行。

Also, the tricky part might be, that I don't want row 35 1 or 40 1, it also contains 1 in B column, but I don't want rows in between entry and exit points, so the next applicable row will be row 70 1 as an entry point (75 1 also to be) 另外,棘手的部分可能是,我不希望行35 1或40 1,它也包含B列中的1,但是我不希望入口点和出口点之间的行,所以下一个适用的行是第70 1行作为入口点(也应为75 1)

This is something I would be able to do in java loop without problem, but I am getting lower performance than I would like, so it's been suggested using db for this kind of operation should be faster. 这是我可以在java循环中完成的事情,但是我得到的性能比我想要的要低,因此建议使用db进行这种操作应该更快。 Is it possible to do such db query? 可以执行这样的数据库查询吗?

If i understand corectly that you need the first valid entry point and its first valid exit point, something like this should do the job 如果我完全理解您需要第一个有效的入口点及其第一个有效的出口点,则应该执行以下操作

    SELECT
    (
        SELECT
            MIN(A)
        FROM
            table
        WHERE
            B = 1
    ) entry,
    A exit,
FROM
    table
WHERE
    A + 20 >= (SELECT
            MIN(A)
        FROM
            table
        WHERE
            B = 1)
AND
    B = 0
LIMIT 1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM