我有一张像
这样的表格 Id name stock_stat_no stock_end_no
----------------------------------------------------
1 a 2 123
2 b 3 65
3 c 191 199
4 d 201 225
5 e 220 223
6 f 221 224
我试过
SELECT * FROM IV_STOCK_DETAILS a
where a.STOCK_START_NO in
(select b.stock_end_no
from IV_STOCK_DETAILS B
where b.stock_start_no
between a.stock_start_no AND
A.STOCK_END_NO
AND B.STOCK_END_NO BETWEEN a.stock_start_no AND A.STOCK_END_NO
AND (a.stock_start_no - A.STOCK_END_NO) !=0
)
ORDER BY cod_stock_branch, stock_start_no;
所以我需要逐行检查所有行以及之前的行,如果它现在开始并且在start&结束前一个打印行的结束。在这种情况下,答案将是 排第2,5,6 ..
我只需要查询
答案 0 :(得分:2)
也许是这样的:
SELECT b.id
FROM iv_stock_details a,
iv_stock_details b
WHERE a.id + 1 = b.id
AND b.stock_stat_no >= a.stock_stat_no
AND b.stock_stat_no < a.stock_end_no
AND b.stock_end_no <= a.stock_end_no
AND b.stock_end_no > a.stock_stat_no;
SQLFiddle:http://sqlfiddle.com/#!2/94722/7
答案 1 :(得分:2)
您可以尝试使用分析功能 线索/延迟。
确切的问题,恕我直言,不清楚:什么是“范围”,什么是“行位于范围”(一个字段可以在范围内)。
所以,让我们重新陈述问题;代替“将第n行与第n + 1行进行比较,如果它位于第n行的范围内,则打印第n + 1行”
我将使用(可能)等价物:“*如果前一行范围[stock_stat_no..stock_end_no]与当前行的范围[stock_stat_no..stock_end_no]相交,则选择行(按名称排序的行)*”
select id
from (select id as id,
name as name,
stock_stat_no as stock_stat_no,
stock_end_no as stock_end_no,
Lag(stock_stat_no) over(order by name) as prior_stock_stat_no,
Lag(stock_end_no) over(order by name) as prior_stock_end_no
from IV_STOCK_DETAILS)
where (prior_stock_stat_no >= stock_stat_no) and
(prior_stock_stat_no <= stock_end_no) or
(stock_stat_no >= prior_stock_stat_no) and
(stock_stat_no <= prior_stock_end_no)