oracle 选择行直到条件满足
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22232282/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Select rows until condition met
提问by Ron M
I would like to write an Oracle query which returns a specific set of information. Using the table below, if given an id, it will return the id and value of B. Also, if B=T, it will return the next row as well. If that next row has a B=T, it will return that, and so on until a F is encountered.
我想编写一个返回一组特定信息的 Oracle 查询。使用下表,如果给定一个 id,它将返回 B 的 id 和值。此外,如果 B=T,它也将返回下一行。如果下一行有 B=T,它将返回那个,依此类推,直到遇到 F。
So, given 3 it would just return one row: (3,F). Given 4 it would return 3 rows: ((4,T),(5,T),(6,F))
所以,给定 3 它只会返回一行:(3,F)。给定 4 它将返回 3 行:((4,T),(5,T),(6,F))
idB
1 F
2 F
3 F
4 T
5 T
6 F
7 T
8 F
id B
1 F
2 F
3 F
4 T
5 T
6 F
7 T
8 F
Thank you in advance!
先感谢您!
采纳答案by MatBailie
Use a sub-query to find out at what point you should stop, then return all row from your starting point to the calculated stop point.
使用子查询找出应该停止的点,然后返回从起点到计算停止点的所有行。
SELECT
*
FROM
yourTable
WHERE
id >= 4
AND id <= (SELECT MIN(id) FROM yourTable WHERE b = 'F' AND id >= 4)
Note, this assumes that the last record is always an 'F'. You can deal with the last record being a 'T' using a COALESCE
.
请注意,这假定最后一条记录始终是“F”。您可以使用COALESCE
.
SELECT
*
FROM
yourTable
WHERE
id >= 4
AND id <= COALESCE(
(SELECT MIN(id) FROM yourTable WHERE b = 'F' AND id >= 4),
(SELECT MAX(id) FROM yourTable )
)