LEAD / LAG功能

时间:2018-02-20 17:55:47

标签: sql hana

我需要优化SQL的帮助。我正在考虑使用LEAD功能,但我不确定......

Article   YEARMONTH   TYPE
123        201612      Z
123        201701      A
456        201703      B    
123        201702
123        201703      AA
456        201704      
456        201705      BB

我只需要为那些未填充TYPE的记录提取上一期间的类型。

Article   YEARMONTH   TYPE
123        201612      Z
123        201701      A
456        201703      B    
123        201702      A - Take from Previous YEARMONTH(In this case its 201701) 
123        201703      AA
456        201704      B   - This is from 201703
456        201705      BB

这就是我得到的:

Issue -If we use COALESCE and LAG

2 个答案:

答案 0 :(得分:1)

lag()是要走的路:

select . . .,
       coalesce(type, lag(type) over (partition by article order by yearmonth))
from t;

不要担心每行执行此操作。这不是SQL的工作原理。相反,请确保在(article, yearmonth)上有一个索引以获得性能。

答案 1 :(得分:0)

@ SQL3026,您可以尝试在样本数据上使用SQL CTE表达式

只是几个笔记;

LEAD和LAG不仅仅提供了获取NOT NULL值的解决方案

我使用了自我JOIN(虽然你没有提到,从Gordon的查询中我认为还有一个标准,即获取前一个类型具有相同的文章值)并在JOIN的ON条件下使用所有标准

为了计算上个月,我使用SQL ROW_NUMBER() function

对行进行了排序

CTE表达式主要使用每行的前一个月的row_number值= 1来过滤JOIN的结果

COALESCE)函数返回第一个非空值。在这种情况下,它只检测最早的文章条目并显示其TYPE列值而不是显示NULL

with cte as (
select 
    t1.article,
    t1.yearmonth,
    t1.type,
    t2.type as prev_type,
    row_number() over (partition by t1.article, t1.YEARMONTH order by t2.YEARMONTH desc) as rn
from article_types as t1
left outer join article_types as t2
    on t1.article = t2.article
    and t2.TYPE is not null
    and t2.yearmonth < t1.yearmonth
order by t1.article, t1.YEARMONTH, t2.YEARMONTH
)
select
    article, yearmonth, type, coalesce(prev_type, type) as prev_type
from cte
where rn = 1

输出如下

enter image description here