简体   繁体   中英

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.

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)

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. 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

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.

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