如果我只有previous
进行排序,如何从表中获取next
或varchar
product_id?
例如,如果我有PRODUCT_NO='20120033'
和PRODUCT_REGISTRATION_NO='yellow'
,我想获得下一条记录PRODUCT_ID which is 4
,我有PRODUCT_NO='20120033'
和PRODUCT_REGISTRATION_NO='green'
,我想得到以前的记录PRODUCT_ID which is 3
我怎样才能做到这一点?
由于
表格结构和数据粘贴在
下面CREATE TABLE MYTAB
(
PRODUCT_ID NUMBER,
PRODUCT_NO VARCHAR2(),
PRODUCT_REGISTRATION_NO VARCHAR2(32)
);
SET DEFINE OFF;
Insert into MYTAB
(PRODUCT_ID, PRODUCT_NO, PRODUCT_REGISTRATION_NO)
Values
(3, '20120033', 'yellow');
Insert into MYTAB
(PRODUCT_ID, PRODUCT_NO, PRODUCT_REGISTRATION_NO)
Values
(4, '20120033', 'green');
Insert into MYTAB
(PRODUCT_ID, PRODUCT_NO, PRODUCT_REGISTRATION_NO)
Values
(5, '20120034', 'wine');
Insert into MYTAB
(PRODUCT_ID, PRODUCT_NO, PRODUCT_REGISTRATION_NO)
Values
(6, '20120034', 'soda');
COMMIT;
答案 0 :(得分:3)
使用lag()和lead()函数:
select *
from (
select product_id,
product_no,
product_registration_no,
lag(product_id) over (partition by product_no order by product_id) as prev_id,
lead(product_id) over (partition by product_no order by product_id) as next_id
from mytab
)
where product_no='20120033'
and product_registration_no='green'
请注意,如果您可以指定要排序的条件,则“previous”和“next”的概念才有意义。这就是窗口定义中order by product_id
的作用。