SQL - 在PARTITION BY语句中创建层次结构

时间:2014-10-20 19:37:59

标签: sql oracle window-functions

我使用以下代码按ID号匹配行:

SELECT *,
    LEAD(ORDER, 1) OVER(PARTITION BY ID_NBR) AS PREV_ORDER
FROM TABLE

在我的数据中,缺少一些ID号。如果(且仅当)缺少ID号,我想通过Cust_Name匹配行。 LEAD / OVER命令可以实现吗?

谢谢,

1 个答案:

答案 0 :(得分:0)

也许你需要这样的东西?

with tab as (
select 1 id, 'n1' cust_name from dual
union all select 2, 'n2' from dual
union all select null, 'n3' from dual
union all select 4, 'n4' from dual
)
select id, cust_name, 
           lag(cust_name ignore nulls) over(order by id) prev_name,
           lead(cust_name ignore nulls) over(order by id) next_name
from tab;

IGNORE NULLS - 在查找滞后/超前值时跳过NULL值。

您可以在ORDER BY

之前添加“PARTITION BY col [,col]”

让ORDER BY与LAG / LEAD功能

是必不可少的